Tuesday, March 1, 2011

Increasing efficiency of loop that uses datenum function?

The following loop takes about 700 seconds to run in octave and 22 seconds to run in matlab when the DJI matrix has 21000 rows. How can I increase the efficiency of this?

for i=1:length(DJI)
DJI2(i,1)=datenum(char(DJI(i,2)),'yyyy-mm-dd');
end

From stackoverflow
  • Did you remember to preallocate DJI2?

    More importantly, you do not need the loop at all. datenum operates on arrays. Try this:

    DJI2=datenum(char(DJI(:,2)),'yyyy-mm-dd');
    

    Jared : Using char() does not seem to allow me to call datenum on the entire array, the code example you gave doesn't work.
    Dima : What is the type of DJI? Is it a cell array? If you have an array A = ['2005-10-10'; '2006-11-12'; ...] then datenum(A, 'yyyy-mm-dd') will work. See if you can convert DJI to something that looks like A.
  • I replaced the loop with the following and got at least a one order of magnitude increase in speed.

    DJI2(:,1) = reshape(datenum(strvcat(DJI(:,2)(:)), length(DJI(:,2)),'yyyy-mm-dd'));
    

0 comments:

Post a Comment