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

8 ビュー (過去 30 日間)
Yeon-Mo Yang
Yeon-Mo Yang 2022 年 1 月 21 日
コメント済み: Yeon-Mo Yang 2022 年 1 月 23 日
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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by