Storing data in matlab matrix using loop

1 次查看(过去 30 天)
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.

采纳的回答

Setsuna Yuuki.
Setsuna Yuuki. 2020-11-29
编辑:Setsuna Yuuki. 2020-11-29
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

更多回答(1 个)

Walter Roberson
Walter Roberson 2020-11-29
编辑:Walter Roberson 2020-11-29
[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

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by