For loop with horzcat

2 ビュー (過去 30 日間)
Ryosuke Saito
Ryosuke Saito 2020 年 4 月 12 日
コメント済み: Ryosuke Saito 2020 年 4 月 12 日
Why does this not success?? Would someone help me correct the code?
A=[1 5; 3 3; 8 6; 4 8; 9 14; 11 11; 13 12; 15 7; 17 15; 1 20]
B=[]
for i=1:5
for j=1:5
B(i,:)=horzcat(B(i,:),A(i+j-1,:));
end
end
I'd like to get this
B=[1 5 3 3 8 6 4 8 9 14;3 3 8 6 4 8 9 14 11 11; 8 6 4 8 9 14 11 11 13 12; 4 8 9 14 11 11 13 12 15 7;9 14 11 11 13 12 15 7 17 15;11 11 13 12 15 7 17 15 1 20]

採用された回答

Matt J
Matt J 2020 年 4 月 12 日
編集済み: Matt J 2020 年 4 月 12 日
Another way,
AA=reshape(A.',[],1).';
B=cell(numel(AA),1);
for i=1:2:11
B{i}=AA(i:i+9);
end
B=cell2mat(B)
  1 件のコメント
Ryosuke Saito
Ryosuke Saito 2020 年 4 月 12 日
Thanks so much! This is exactly what I'd like to do and I found this works!!

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

その他の回答 (1 件)

Matt J
Matt J 2020 年 4 月 12 日
編集済み: Matt J 2020 年 4 月 12 日
horzcating in for-loops is bad practice. Better to do,
AA=reshape(A.',[],1).';
B=AA( (1:10)+(0:2:10).' )
  2 件のコメント
Ryosuke Saito
Ryosuke Saito 2020 年 4 月 12 日
Thanks for your comment. I am sorry that I set up a simple table as the contents of A here. Actual contents of A in the computation I am trying to do is much complicated. So the proposed solution is not useful.
Matt J
Matt J 2020 年 4 月 12 日
My solution is independent of the contents of A.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by