Hi Raquel,
For loops are going to be slower, but it is interesting to seet how much and under what circumstances. The following code reproduces Matrix2 with a couple of for loops, and it is as for-loopy as possible because it goes element-by-element. For the case you have, typical computation times are
N=20; M=30; O=50; P=10;
Elapsed time is 0.001468 seconds.
Elapsed time is 0.007577 seconds.
They are both so fast that it hardly matters which you do. Now try increasing all dimensions by a factor of 10. (I only increased P by a factor of 4 because I didn't want to wait around too long).
N=200; M=300; O=500; P=40;
Elapsed time is 3.641819 seconds.
Elapsed time is 54.831857 seconds.
You can see that the effect is not good, the for loop being about 15 times slower. Somewhere in the middle is a size where the for loop execution time may be tolerable.
'Vectorized' etc. code is not automatically faster than the for loop equivalent. Sometimes it's slower. But in this case, compared to using the handy Matlab functions like permute, for loops are both slower and harder to program.
N=20; M=30; O=50; P=10;
tic
a1 = N*O
a2 = M*P
Matrix1 = reshape([1:a1*a2],[a1,a2]);
Matrix2 = reshape(Matrix1,[N,a1/N,M,a2/M]) ;
Matrix2 = permute(Matrix2,[1 4 3 2]);
Matrix2 = reshape(Matrix2,[N*a2/M, M*a1/N]);
toc
tic
Mfor = zeros(N*P,M*O);
for r = 1:N*P
for c = 1:M*O
Mfor(r,c) = M*N*O*floor((r-1)/N) + rem(r-1,N)+1 ...
+N*floor((c-1)/M) + N*O*rem(c-1,M);
end
end
toc
max(abs(Matrix2-Mfor),[],'all')
1 Comment
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/611791-convert-permute-and-reshape-to-for#comment_1054461
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/611791-convert-permute-and-reshape-to-for#comment_1054461
Sign in to comment.