While loop to count iterations
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Kyle Langford
le 14 Mar 2021
Réponse apportée : Image Analyst
le 14 Mar 2021
Hello, I am new to matlab, and I am not sure how to use loops.
I am being asked to count the number of terms that keeps the equation k^2+2*k <100.
This is what I have, but all it is giving me is: count=1
count=0;
k=1:10;
while (k < 100)
k=k.^2+2*k;
count=count+1
end
0 commentaires
Réponse acceptée
Image Analyst
le 14 Mar 2021
k = 1 : 10;
loopCounter = 1;
while loopCounter < length(k)
theSum = k(loopCounter) .^ 2 + 2 * k(loopCounter)
if theSum >= 100
break; % Quit the loop
end
loopCounter=loopCounter+1
end
loopCounter % Show final value
0 commentaires
Plus de réponses (1)
Walter Roberson
le 14 Mar 2021
k=1:10
is a vector.
while k<100
is a vector test equivalent to 10^2+2*10 = 120 and that is not less than 100 so the test is no longer true for all of the elements.
while all(k<100)
But after 1 step, the 10 component of k gets mapped to
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!