简体   繁体   中英

Matlab transform 2D matrix to 3D matrix

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,[]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM