Storing data in matlab matrix using loop

조회 수: 2 (최근 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 CenterFile Exchange에서 Loops 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