简体   繁体   中英

Understanding Vectorization

I'm trying to make some code more efficient, and am wondering how to vectorize this:

%==========================================================================
% MinutesInDayTable.m
% 
% Creates a table identifying every minute as an integer from 0 to 2400.

minuteTableInDay=zeros(24*60,1);
k=1;
for i=1:24
    for j=1:60
        minuteTableInDay(k) = ((i-1)*100+(j-1))*100;
        k=k+1;
    end
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ end of code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here's another one:

minuteTableInDay = (datestr(0:1/24/60:1, 'HHMMSS')-48) * 10.^(5:-1:0)'

Have fun :)

That's easy, the general way to vectorize this computation is:

[I, J] = meshgrid(1:24, 1:60);                      %// 2-D arrays for I and J
minuteTableInDay = ((I - 1) * 100 + (J - 1)) * 100; %// Compute all values at once
minuteTableInDay = minuteTableInDay(:);             %// Convert to a column vector

The key to vectorizing this is supplying MATLAB with all the values, so that the operations can be performed for all elements at once.

In your case, your code contains basic arithmetic functions so you can further reduce your code (similar to Oleg's suggestion):

minuteTableInDay = bsxfun(@plus, (0:59)', (0:23) * 100) * 100;

You can create time that goes from 0,...,115900,120000,...,235900 :

out = bsxfun(@plus, (0:59)' , 0:23)*100;
out = out(:);

If you want it to be 100,...,115900,120000,...,240000 , add this line:

out = [out(2:end); 240000]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM