While loop to count iterations

15 次查看(过去 30 天)
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

采纳的回答

Image Analyst
Image Analyst 2021-3-14
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

更多回答(1 个)

Walter Roberson
Walter Roberson 2021-3-14
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by