Efficient way to reshape data

7 ビュー (過去 30 日間)
David Velasco
David Velasco 2022 年 11 月 1 日
編集済み: Bruno Luong 2022 年 11 月 1 日
I am looking for an efficient way to reshape a matrix. Seems like a simple process, but I can't seem to get it right.
I have the following example. The real data will be much larger, but always an [n 3] matrix.
data = [ 1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24];
And I'd like to end up with something like this:
>> data2
data2(:,:,1) =
1 2 3
4 5 6
data2(:,:,2) =
7 8 9
10 11 12
data2(:,:,3) =
13 14 15
16 17 18
data2(:,:,4) =
19 20 21
22 23 24
I'm sure using combinations of transpose, reshapre, repmat, and/or similar I can get to this with just one line of code, but I'm struggling to get there. I can use the following for loop and that does the job:
data2 = nan(2,3,4);
for i = 1:4
data2(:,:,i) = data(i*2-1:2*i,1:3);
end
But I'm sure there's a more elegant and efficient way to do this. Any suggestions are appreciated.

採用された回答

David Hill
David Hill 2022 年 11 月 1 日
data = [ 1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24];
permute(reshape(data',3,2,[]),[2 1 3])
ans =
ans(:,:,1) = 1 2 3 4 5 6 ans(:,:,2) = 7 8 9 10 11 12 ans(:,:,3) = 13 14 15 16 17 18 ans(:,:,4) = 19 20 21 22 23 24
  1 件のコメント
David Velasco
David Velasco 2022 年 11 月 1 日
Ah, permute! Of course. Thank you.
Simple and more than twice as fast as my for loop.

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

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2022 年 11 月 1 日
編集済み: Bruno Luong 2022 年 11 月 1 日
This avoids inner transposition
permute(reshape(data,2,[],3),[1 3 2])

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by