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

2 visualizzazioni (ultimi 30 giorni)
Jake il 12 Lug 2022
Modificato: Stephen23 il 12 Lug 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.
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Risposta accettata

Stephen23 il 12 Lug 2022
Modificato: Stephen23 il 12 Lug 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
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by