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

MATLABmatrix manipulation

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 !!

Best 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(:,:,:)