Support Articles
Technical Computing
Using DATENUM and DATEVEC in MATLAB 7
Code that contains datenum or datevec may be much slower in MATLAB 7 than in MATLAB 6.5.
I use tic and toc to calculate the amount of time it takes to convert 1000 date strings (containing a date) to serial date numbers. The results is that MATLAB 7.01 is more than 40% slower than MATLAB 6.5.1.
% In MATLAB 6.5.1:
tic, for k = 1:1000, d = datenum('25-Oct-2004'); end, toc
elapsed_time =
0.9840
% In MATLAB 7:
tic, for k = 1:1000, d = datenum('25-Oct-2004'); end, toc
Elapsed time is 1.406000 seconds.
The MATLAB 7 implementation of datenum and datevec does much more work to try to guess from a much longer list of supported formats and languages what the format of your date string is. As a result, the conversion between date strings and date numbers will take longer. However you can reduce the time taken by providing datenum or datevec with the optional date format string.
The conversion of the 1000 date numbers now takes about 40% of the time it took in MATLAB 6.5. In addition, since we (South Africans) tend to use the dd/mm/yyyy format, this is easily achieved by specifying the format string:
For those interested in a fast datevec like function, take a look at the function datestr2vec contributed to MATLAB Central by Per Isakson.
% In MATLAB 7:
tic, for k = 1:1000, d = datenum('25-Oct-2004','dd-mmm-yyyy'); end, toc
theDate = datenum('25/10/2004','dd/mm/yyyy')
Elapsed time is 0.485000 seconds.
theDate =
732245
In MATLAB 7.0, a conversion from a date string which contains only date information (i.e. no time) to a date number, sometimes results in an unexpected fraction.
datevec(['16-Apr-07';'27-Apr-07'])
ans =
2007 4 16 0 0 0
2007 4 26 23 0 0
This is a bug in MATLAB 7.0, and occurs when the time zone is set to (GMT +02:00) Harare, Pretoria. In most cases, you can work around this bug by manually separating the date string into year, month and day and then calling datevec. Alternatively and preferably, you should update to Release 14 Service Pack 1 which fixes this bug.