Storing data in matlab matrix using loop

5 vues (au cours des 30 derniers jours)
MM
MM le 29 Nov 2020
Hello, I am running a loop
i=1;
for k1=2:1:20
for k2=2:1:20
for k3 = 2:1:20
M = [k1,k2,k3];
if sum(M,'all')==20
%A = M (matrix containing all three elements, k1,k2,k3) - CODE NEEDED here
end
end
end
end
I want to store all the condition abiding matrices M in matrix A, here, matrix A is the list of all the M matrices.
Thanks.

Réponse acceptée

Setsuna Yuuki.
Setsuna Yuuki. le 29 Nov 2020
Modifié(e) : Setsuna Yuuki. le 29 Nov 2020
You can try use cell()
i=1;
for k1=2:1:20
for k2=2:1:20
for k3 = 2:1:20
M = [k1,k2,k3];
if sum(M,'all')==20
A{i} = M;
i=i+1;
end
end
end
end
A{1}
ans =
2 2 16
A{2}
ans =
2 3 15

Plus de réponses (1)

Walter Roberson
Walter Roberson le 29 Nov 2020
Modifié(e) : Walter Roberson le 29 Nov 2020
[K1, K2, K3] = ndgrid(2:1:20, 2:1:20, 2:1:20);
M = K1 + K2 + K3;
mask = M == 20;
A = [K1(mask), K2(mask), K3(mask)];
size(A)
ans = 1×2
120 3
By the way: there is no point going as high as 20 in the vectors. You want a sum of 20 and the mininum value for each is 2, so the maximum that it is possible for any valid entry to be is 20 - 2 - 2 = 16, so you might as well only do 2:16

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by