How to reshape matrix without loop?

1 回表示 (過去 30 日間)
John
John 2017 年 7 月 26 日
編集済み: John 2017 年 7 月 26 日
Want to rearrange the matrix A(a,b,c,d) to B(b,c1,c2,d,a), where a,b,c,d are dimensions, c=c1*c2. If known c1=3, for example, B should be:
[a,b,c,d]=size(A);
C=permute(A,[2,3,4,1]);
c2=fix(c/c1);
B=zeros(b,c1,c2,d,a);
for nc=1:c1
B(:,nc,:,:,:)=C(:,nc:c1:end,:,:);
end
Can it be done more elegantly and without the loop?

回答 (1 件)

John D'Errico
John D'Errico 2017 年 7 月 26 日
WTP? Effectively two lines, one more to get the size of A if you don't know it already.
[a,b,c,d] = size(A);
B = reshape(A,[a,b,c1,c/c1,d]);
B = permute(B,[2 3 4 5 1]);
There is no need to use fix, because if c is not exactly divisible by c1, then A won't have the correct number of elements for a reshape anyway.
  1 件のコメント
John
John 2017 年 7 月 26 日
編集済み: John 2017 年 7 月 26 日
Hi, John: Will this make the dimension c1 to be the index (1,4,7,10...),(2,5,8,11...), (3,6,9,12...) from c respectively? Thanks.

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by