How to save a matrix in a row of another matrix? MATLAB

I have a 3D matrix, and I want to save each 2D component of this in a row of another 2D matrix, which has many rows as the 3rd dimension of a 3D matrix.

How can i do this?

enter image description here

+5
source share
3 answers

With permute and reshape -

 reshape(permute(A,[3 2 1]),size(A,3),[]) 

Run Example -

 >> A A(:,:,1) = 7 1 7 5 3 4 8 5 9 4 2 6 A(:,:,2) = 7 7 2 4 7 6 5 6 3 2 9 3 A(:,:,3) = 7 7 5 3 3 9 2 8 5 9 2 3 >> reshape(permute(A,[3 2 1]),size(A,3),[]) ans = 7 1 7 5 3 4 8 5 9 4 2 6 7 7 2 4 7 6 5 6 3 2 9 3 7 7 5 3 3 9 2 8 5 9 2 3 
+5
source

If you do not mind a little indexing insanity ...

You can build a linear index with the appropriate form , which is applied to the original array, will give the desired result:

 B = A(bsxfun(@plus, (1:L*M:L*M*N).', reshape(bsxfun(@plus, (0:L:L*M-1).', 0:L-1),1,[]))); 

Example:

 >> A = randi(10,2,3,4)-1; %// example array; size 2x3x4 >> A A(:,:,1) = 5 3 2 9 8 9 A(:,:,2) = 8 7 4 9 8 6 A(:,:,3) = 3 4 8 0 4 4 A(:,:,4) = 2 8 8 4 6 7 

Result:

 >> B B = 5 3 2 9 8 9 8 7 4 9 8 6 3 4 8 0 4 4 2 8 8 4 6 7 
+2
source

This is easily done using the MATLABs matrix expansion syntax:

 A=ones(N,M,O); B=zeros(O,N*M); for ii=1:size(A,3) aux=A(:,:,ii); % aux is NxM B(ii,:)=aux(:); % unroll! end 

(notice, I called O what you call N in your pictures)

+1
source

Source: https://habr.com/ru/post/1232611/


All Articles