how to avoid 'two for loop'?
显示 更早的评论
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...
采纳的回答
更多回答(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.
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!