Efficiently converting a 3d matrix to a 2d matrix

Hello,
I would like to convert a 3d matrix into a 2d matrix. I want the 3rd dimension to be concatenated along dimension 1 in the 2d matrix. In the code below, the variable 'desired' illustrates what I want to achieve, but I want to do it more efficiently than via a for a loop. I tried doing the same with reshape (see variable B) but can't get it to produce the output I desire.
A(:,:,1) = ones(2,2);
A(:,:,2) = 2*ones(2,2);
A(:,:,3) = 3*ones(2,2);
desired = [];
for n = 1:size(A,3)
desired = cat(1,desired,A(:,:,n));
end
B = reshape(A,[],size(A,2),1);
Any advice would be much appreciated. Thanks for reading.

 採用された回答

the cyclist
the cyclist 2011 年 3 月 21 日

33 投票

You can permute the 2nd and 3rd dimension before doing the reshape:
>> C = permute(A,[1 3 2]);
>> C = reshape(C,[],size(A,2),1)

9 件のコメント

Andrew Newell
Andrew Newell 2011 年 3 月 21 日
Elegant!
Mohammed Samdani
Mohammed Samdani 2013 年 1 月 30 日
converting 3D to 2D matrix row wise
Salvador Pacheco-Gutierrez
Salvador Pacheco-Gutierrez 2013 年 10 月 4 日
Thank you! Excelent!
Vasileios Siomos
Vasileios Siomos 2017 年 3 月 25 日
Thanks a bunch this is so elegant!
Zoe
Zoe 2018 年 2 月 24 日
Save my life!
IndikaWM
IndikaWM 2018 年 4 月 5 日
mine too! Thank you.
Linjun He
Linjun He 2018 年 12 月 25 日
Thank you!!!
Yue Zhang
Yue Zhang 2019 年 2 月 23 日
Thank you.
Sem Diaz
Sem Diaz 2019 年 12 月 4 日
How can you convert it back?

サインインしてコメントする。

その他の回答 (2 件)

Andrew Newell
Andrew Newell 2011 年 3 月 21 日

5 投票

You can do it with cell arrays:
Acell = num2cell(A,[1 2]); % put each page of A into a cell
Acell = reshape(Acell,size(A,3),1); %make the cell array a vector
desired = cell2mat(Acell);
EDIT: the solution by @the cyclist is nicer for this particular problem, but be careful about generalizing it. For example, suppose you want to pack your matrices into a 2x2 array:
A(:,:,1) = ones(2,2);
A(:,:,2) = 2*ones(2,2);
A(:,:,3) = 3*ones(2,2);
A(:,:,4) = 4*ones(2,2);
Acell = num2cell(A,[1 2]);
Acell = reshape(Acell,2,2);
desired = cell2mat(Acell)
desired =
1 1 3 3
1 1 3 3
2 2 4 4
2 2 4 4
C = permute(A,[1 3 2]);
C = reshape(C,[],4,1)
C =
1 3 1 3
1 3 1 3
2 4 2 4
2 4 2 4
Omar Mian
Omar Mian 2011 年 3 月 21 日

1 投票

Thank you Andrew & cyclist,
Both solutions work. Cyclist's permute solution is more efficient, taking approx approx 17% of the time used by the cell array solution.

カテゴリ

製品

質問済み:

2011 年 3 月 21 日

コメント済み:

2019 年 12 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by