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

8 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2022-1-21
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

更多回答(1 个)

William Rose
William Rose 2022-1-21
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.

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by