Reshaping a 2D matrix to a 3D one with specific ordering

Hello,
I have a nxn matrix that i would like to reshape into a (2 x 2 x :) matrix without using any loops and in this way but with reshape:
an example with "n = 4" and:
A = [1 2 3 4;...
5 6 7 8;...
9 10 11 12;...
13 14 15 16]
gives: B(: , : ,1) = [1 2;
5 6]
B(: , : ,2) = [3 4;
7 8]
B(: , : ,3) = [9 10;
13 14]
B(: , : ,4) = [11 12;
15 16]
Thanks !!

 Accepted Answer

A = [1 2 3 4;...
5 6 7 8;...
9 10 11 12;...
13 14 15 16]
[m n] = size(A);
B = permute(reshape(A,[2 m/2 2 n/2]),[1 3 4 2]);
B = B(:,:,:)

5 Comments

Just one more question: after that i do several transformation on B (rotations) and at the end i want to reshape B in order to get a similar matrix to A (same size and elements ordered in the same way). How could i do it ?
AA = reshape(ipermute(reshape(B,[2 2 n/2 m/2]), [1 3 4 2]), [m n])

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2020b

Community Treasure Hunt

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

Start Hunting!