Storing data in matlab matrix using loop

1 回表示 (過去 30 日間)
MM
MM 2020 年 11 月 29 日
編集済み: Walter Roberson 2020 年 11 月 29 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by