Need help with FOR loop with 3 indexes
Afficher commentaires plus anciens
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.
Réponses (3)
Andrei Bobrov
le 13 Avr 2011
is the same, without loop
[k2,i2,j2] = meshgrid(0:10:100);
s2 = [i2(:) j2(:) k2(:)];
a2 = s2(sum(s2,2)==100,:);
Jan
le 13 Avr 2011
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
le 13 Avr 2011
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.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!