How do I convert a 2d matrix to a 3d matrix and vice versa efficiently?

8 views (last 30 days)
Hello,
In this post, I need converting 3d matrix A to 2d matrix C1 and revese case.
When I try to convert 2d matrix C1 back to 3d matrix A, it failed I am not sure the reasons. (sum(A-h3,'all'))
In reshape I should do [2,3,4] not [2,4,3], but I am wondering why I should change the order in size.
So many thanks in advance.
>> size(A) % ans = 2 3 4
>> size(C1) % ans = 8 3
%%%% code begin
A(:,:,1) = [1 2;3 4;5 6]';
A(:,:,2) = [10 20;30 40;50 60]';
A(:,:,3) = [11 21;31 41;51 61]';
A(:,:,4) = [100 200;300 400;500 600]';
C1 = [A(:,:,1);A(:,:,2);A(:,:,3);A(:,:,4)];
permute(reshape(C1,size(A)), [1 3 2])
s1=size(A,1); s2=size(A,2); s3=size(A,3);
permute(reshape(C1,[s1,s3,s2]), [1 3 2]) % need a comment for reverseing order [2,4,3] not [2,3,4]
%permute(reshape(C1,[2,4,3]), [1 3 2])
h1=permute(A,[1 3 2]); % c/d2, v1 (1/2)
h2=reshape(h1,[],size(A,2),1);
%h3=permute(reshape(h2,size(A)), [1 3 2])
h3=permute(reshape(h2,[s1,s3,s2]), [1 3 2]) % need a comment for reverseing order
sum(A-h3,'all')
%%%% code end

Accepted Answer

Stephen23
Stephen23 on 21 Jan 2022
format compact
A(:,:,1) = [1,2;3,4;5,6]';
A(:,:,2) = [10,20;30,40;50,60]';
A(:,:,3) = [11,21;31,41;51,61]';
A(:,:,4) = [100,200;300,400;500,600]'
A =
A(:,:,1) = 1 3 5 2 4 6 A(:,:,2) = 10 30 50 20 40 60 A(:,:,3) = 11 31 51 21 41 61 A(:,:,4) = 100 300 500 200 400 600
C1 = reshape(permute(A,[2,1,3]),size(A,2),[]).'
C1 = 8×3
1 3 5 2 4 6 10 30 50 20 40 60 11 31 51 21 41 61 100 300 500 200 400 600
[A(:,:,1);A(:,:,2);A(:,:,3);A(:,:,4)] % your desired C1 matrix
ans = 8×3
1 3 5 2 4 6 10 30 50 20 40 60 11 31 51 21 41 61 100 300 500 200 400 600
B = permute(reshape(C1.',[3,2,4]),[2,1,3])
B =
B(:,:,1) = 1 3 5 2 4 6 B(:,:,2) = 10 30 50 20 40 60 B(:,:,3) = 11 31 51 21 41 61 B(:,:,4) = 100 300 500 200 400 600

More Answers (1)

William Rose
William Rose on 21 Jan 2022
A(:,:,1) = [1 2;3 4;5 6]';
A(:,:,2) = [10 20;30 40;50 60]';
A(:,:,3) = [11 21;31 41;51 61]';
A(:,:,4) = [100 200;300 400;500 600]';
C1 = [A(:,:,1);A(:,:,2);A(:,:,3);A(:,:,4)];
D=permute(reshape(C1,[2 2 2 3]),[1 4 3 2]);
E=reshape(D,[2 3 4]);
fprintf('size(A)=%d by %d by %d, size(E)=%d by %d by %d, sum(A-E)=%.1f.\n',...
size(A),size(E),sum(A-E,'all'));
size(A)=2 by 3 by 4, size(E)=2 by 3 by 4, sum(A-E)=0.0.
Try it.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!