How to Stop FOR loop when "answer" is reached, and display answer?

2 ビュー (過去 30 日間)
Alexis
Alexis 2022 年 12 月 2 日
コメント済み: Star Strider 2022 年 12 月 2 日
Simple "throwing a ball" physics problem - someone throws a ball, I want to know what time the ball touches the ground.
I am trying to create a loop that "stops" when the height of the ball reaches 0.
Then I want to display what time the ball reaches height = 0.
Here is what I have sofar:
%When does ball Reach the Surface?
for t = 0:0.01:6.2
if height_earth = 0
disp('The Time when the ball lands is: %4.2f\n', time)
else
disp('The Ball doesnt Touch the Ground')
end
end
I get the display "The Ball doesnt Touch the Ground" 621 times, and have a feeling if "if height_earth = 0" were valid matlab syntax, a would get the entire time array.

回答 (1 件)

Star Strider
Star Strider 2022 年 12 月 2 日
See the documentation on the break function.
  2 件のコメント
Alexis
Alexis 2022 年 12 月 2 日
What about for the solving? How would I get it to display the time when height = 0?
Star Strider
Star Strider 2022 年 12 月 2 日
Put the break call after the disp call.
Also, the comparison requires a ‘double equal’ —
if height_earth == 0
.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by