How do I convert a 2d matrix to a 3d matrix and vice versa efficiently?
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Yeon-Mo Yang
le 21 Jan 2022
Commenté : Yeon-Mo Yang
le 23 Jan 2022
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 commentaires
Réponse acceptée
Stephen23
le 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]'
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])
Plus de réponses (1)
William Rose
le 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'));
Try it.
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!