Why slow conversion from date in Matlab time to day of year?

1 回表示 (過去 30 日間)
K E
K E 2015 年 5 月 18 日
コメント済み: Peter Perkins 2015 年 6 月 3 日
I have a vector of dates in Matlab time convention which I need to convert to day of the year. The following code is slow (9 seconds) even though it is using builtin Matlab functions. What do you recommend to speed it up?
timeGmt = datenum(1996,1,1):1/24:now; % Long vector of dates covering many years
timeGmt = timeGmt'; % Change from row vector to column vector for compatibility in next line
yearDay = timeGmt - ...
datenum(str2num(datestr(timeGmt, 10)), 1, 1) ... % Subtract off first day of this year
+ 1; % Add a day so that first day of year is day 1

採用された回答

James Tursa
James Tursa 2015 年 5 月 18 日
編集済み: James Tursa 2015 年 5 月 18 日
Try this variation using datevec instead of datestr:
vecGmt = datevec(floor(timeGmt)); % Set hms to 0's using floor
vecGmt(:,2:3) = 1; % Set month and day to Jan 1
yearDay = timeGmt - datenum(vecGmt) + 1;
  3 件のコメント
James Tursa
James Tursa 2015 年 5 月 18 日
Try the edited version using floor instead of setting the hms to 0's directly.
K E
K E 2015 年 5 月 18 日
0.04s. very nice.

サインインしてコメントする。

その他の回答 (1 件)

Peter Perkins
Peter Perkins 2015 年 5 月 18 日
編集済み: Walter Roberson 2015 年 5 月 19 日
In R2014b or later, use datetime. On a not particularly fast Win7 machine:
>> timeGmt = '1-Jan-1996':hours(1):datetime('now');
>> tic, dayOfYear = day(timeGmt,'dayofyear'); toc
Elapsed time is 0.041145 seconds.
  2 件のコメント
K E
K E 2015 年 5 月 26 日
編集済み: K E 2015 年 5 月 26 日
I don't seem to have the function day.m but it may be part of the Financial toolbox .
Peter Perkins
Peter Perkins 2015 年 6 月 3 日
If you have R2014b or later, you have the day function. It is a method of the datetime class, which was introduced in R2014b.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by