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

1 visualización (últimos 30 días)
Jake
Jake el 12 de Jul. de 2022
Editada: Stephen23 el 12 de Jul. de 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.

Respuesta aceptada

Stephen23
Stephen23 el 12 de Jul. de 2022
Editada: Stephen23 el 12 de Jul. de 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

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by