248 Accelerating MATLAB
®
Performance
As another example:
% Loop variant
data = rand(10,20,30); % 10x20x30
for idx = 1 : size(data,3)
a(idx) = sum(sum(data(:,:,idx)));
end
% Vectorized variant
idx = 1 : size(data,3)
a(idx) = sum(sum(data(:,:,idx)));
% Simpler variant
a = reshape(sum(sum(data)), 1, []); % reshape 1x1x30 1x30
Sometimes the transformation is not so simple, since there are dependencies between
the loop iterators:
% Loop variant
for i = 1 : num_total_days
for j = 1 : num_days_later-1
if (i+j) <= num_total_days+1
for k = 1 : num_stocks
if data(i,j+1,k) >0
data2(i,j,k) = (data(i,j+1,k) / data(i,1,k)) - 1;
end
end
end
end
end
% Vectorized variant, in 2 phases:
% Phase 1 - divide all elements by the ...