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

2 Ansichten (letzte 30 Tage)
Jake
Jake am 12 Jul. 2022
Bearbeitet: Stephen23 am 12 Jul. 2022
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.

Akzeptierte Antwort

Stephen23
Stephen23 am 12 Jul. 2022
Bearbeitet: Stephen23 am 12 Jul. 2022
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

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by