필터 지우기
필터 지우기

While loop to count iterations

조회 수: 3 (최근 30일)
Kyle Langford
Kyle Langford 2021년 3월 14일
답변: Image Analyst 2021년 3월 14일
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