MATLAB Answers

Convert permute and reshape to for

5 views (last 30 days)
Hello everybody,
I am trying to find an alternative to the last 3 lines of code:
N=20; M=30; O=50; P=10;
all_1 = N*O
all_2 = M*P
Matrix1 = reshape([1:all_1*all_2],[all_1,all_2])
Matrix2 = reshape(Matrix1,[N,all_1/N,M,all_2/M])
Matrix2 = permute(Matrix2,[1 4 3 2])
Matrix2 = reshape(Matrix2,[N*all_2/M, M*all_1/N])
Maybe I can use some loops, because I want to compare the efficency of two different methods.
Thanks

  1 Comment

John D'Errico
John D'Errico on 12 Oct 2020
You want to write a loop for that instead? Why in the name of god would you? Instead of nice efficient code that uses very little time, you want to write complicated loops to do the same thing?
You should see that a reshape requires very little time, since nothing in memory changes. All MATLAB needs to do is change an internal flag on the variable that indicate the shape. The permute takes a little more time, but still relatively little, because it is entirely written using fast compiled code. Loops would be a terrible way to achieve these things.

Sign in to comment.

Accepted Answer

David Goodmanson
David Goodmanson on 12 Oct 2020
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. % reshape
Elapsed time is 0.007577 seconds. % for loop
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. % reshape
Elapsed time is 54.831857 seconds. % for loop
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;
% N=200; M=300; O=500; P=40;
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') % should be 0

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!