Need help with FOR loop with 3 indexes
이전 댓글 표시
I need help with FOR loop with three indexes (i, j, k). Each index varies from 0 to 100 in 10 increments. However these 3 indexes need to add to 100 therefore ignoring any combinations which do not add to 100. There are 66 combinations which add to 100. Basically I just want to loop through all these 66 combinations.
For example i = 0, j = 10, k = 90 i = 0, j = 20, k = 80 i = 0, j = 30, k = 70 and so on.
Any suggestions would be greatly appreciated.
답변 (3개)
Andrei Bobrov
2011년 4월 13일
is the same, without loop
[k2,i2,j2] = meshgrid(0:10:100);
s2 = [i2(:) j2(:) k2(:)];
a2 = s2(sum(s2,2)==100,:);
Jan
2011년 4월 13일
Another loop version - but I've voted the MESHGRID approach of abobroff.
a = [];
for i = 0:10:100
for j = 0:10:100
k = 100 - i - j;
if k >= 0
a = [a; i, j ,k];
else
break;
end
end
end
Paulo Silva
2011년 4월 13일
a=[];
for i=0:10:100
for j=0:10:100
for k=0:10:100
s=i+j+k;
if s==100
a=[a; i j k];
end
end
end
end
The code gives you the variable a that contains the values of i j k that satisfy your condition.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!