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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by