I have a 2D Matrix A like:
A = [ 1 2 3 4 5 6;
7 8 9 10 11 12;
1 2 3 4 5 6;
7 8 9 10 11 12;]
I want to transform this 2D Matrix to a 3D Matrix B with size 2X3X4, like:
B(:,:,1) = [1 2 3; 7 8 9];
B(:,:,2) = [1 2 3; 7 8 9];
B(:,:,3) = [4 5 6; 10 11 12];
B(:,:,4) = [4 5 6; 10 11 12];
now what I do is first transform this 2D Matrix A to cell type C with mat2cell and then use cat to transform it 3D Matrix B, but it is too complicated, since I do not need this cell C at all.
Can some give me any advice how I can transform A to B directly and elegantly?
Thanks!
You could do something like this -
[m,n] = size(A);
nr = 2; % Number of rows in o/p
nc = 3; % Number of cols in o/p
out = reshape(permute(reshape(A,nr,m/nr,nc,[]),[1,3,2,4]),nr,nc,[]);