Azzera filtri
Azzera filtri

While loop to count iterations

22 visualizzazioni (ultimi 30 giorni)
Kyle Langford
Kyle Langford il 14 Mar 2021
Risposto: Image Analyst il 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

Risposta accettata

Image Analyst
Image Analyst il 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

Più risposte (1)

Walter Roberson
Walter Roberson il 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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by