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
댓글 수: 0
채택된 답변
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]'
C1 = reshape(permute(A,[2,1,3]),size(A,2),[]).'
[A(:,:,1);A(:,:,2);A(:,:,3);A(:,:,4)] % your desired C1 matrix
B = permute(reshape(C1.',[3,2,4]),[2,1,3])
추가 답변 (1개)
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'));
Try it.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!