Filter löschen
Filter löschen

While loop to count iterations

3 Ansichten (letzte 30 Tage)
Kyle Langford
Kyle Langford am 14 Mär. 2021
Beantwortet: Image Analyst am 14 Mär. 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

Akzeptierte Antwort

Image Analyst
Image Analyst am 14 Mär. 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

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 14 Mär. 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by