简体   繁体   中英

How can I store a matrix in a row of another matrix? MATLAB

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

How can I do this?

在此输入图像描述

With permute & reshape -

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

Sample run -

>> 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

If you don't mind a little indexing madness...

You can build a linear index with the appropriate shape , which applied on 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

That is easily done with MATLABs matrix unrolling 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

(note I called O the thing you call N in your pictures)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM