How can I store all outputs from a nested for loop?

1 回表示 (過去 30 日間)
Jake
Jake 2022 年 7 月 12 日
編集済み: Stephen23 2022 年 7 月 12 日
I know this might be a common problem, and tried a lot of different answers posted under similar questions. Anyway, here's a basic idea.
a = rand(2,3);
b = rand(2,3);
c = rand(2,3);
for i=1:length(a(:,1))
for j=1:length(a(1,:))
z = [a(i,j), b(i,j), c(i,j)]
end
end
As you can see, I get a 1x3 matrix for z in every iteration, but I want to store them, so I'd have a z as 6x3. I know I haven't preallocated for z here, btw.

採用された回答

Stephen23
Stephen23 2022 年 7 月 12 日
編集済み: Stephen23 2022 年 7 月 12 日
This is easier using linear indexing:
a = rand(2,3);
b = rand(2,3);
c = rand(2,3);
z = nan(numel(a),3); % preallocate
for k = 1:numel(a)
z(k,:) = [a(k),b(k),c(k)];
end
display(z)
z = 6×3
0.8970 0.9894 0.0327 0.1664 0.5844 0.5157 0.1946 0.8872 0.6354 0.5858 0.9135 0.5917 0.1652 0.9554 0.0871 0.9033 0.2481 0.6914

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by