how to avoid 'two for loop'?
Show older comments
I don't know how to avoid using for loop, because It takes a lot of time to calculate.
Below is the code to change.
for i = 1 : 26
for j = 1 : 86400
B(86400*(i-1)+j , :) = A(26*(j-1)+i, :);
end
end
I find solutions instead of for loop, like 'repmat' or 'bsxfun', ... but I have no ideas how to shorten the time.
Please give me a hand...
Accepted Answer
More Answers (1)
If B is pre-allocated, the computing time is:
A = rand(2246400, 5); % Test data
tic;
B = zeros(size(A));
for i = 1 : 26
for j = 1 : 86400
B(86400*(i-1)+j , :) = A(26*(j-1)+i, :);
end
end
toc
% Elapsed time: 1.37 sec
With the auto-expanding of R2016b:
B(86400 * (0:25) + (1:86400).', :) = A(26 * (0:86399).' + (1:26), :);
Without auto-expanding for R<=2016b:
indexB = bsxfun(@plus, 86400 * (0:25), (1:86400).');
indexA = bsxfun(@plus, 26 * (0:86399).', 1:26);
B(indexB, :) = A(indexA, :);
% Elapsed time: 0.24sec
Akira Agata's code is not completely vectorized and uses 0.23 sec, so it is slightly faster then the complete vectorization. Nice! The creation of the large index matrices wastes a lot of time.
But now take the problem for the viewpoint of permuting the blocks of the array:
AA = reshape(A, 26, 86400, []);
AA = permute(AA, [2,1,3]);
B = reshape(AA, 86400*26, []);
% Elapsed time: 0.16 sec
The internal methods for permuting (a kind of transposing in multi-dim arrays) are faster than the explicit indexing. In addition the programmer has less chances for typos.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!