while loop with else if statement

12 ビュー (過去 30 日間)
Stephanie Figueroa
Stephanie Figueroa 2021 年 3 月 19 日
回答済み: Walter Roberson 2021 年 3 月 19 日
I've attached a screenshot below, wondering why I can't get the loop to go through each if/elseif/else statement. I keep getting the first fprintf output under my first if statement no matter what value i get. What am i missing?

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 3 月 19 日
You have
if Gforce >= 7 || Gforce < 9
Consider the opposite for a moment:
if ~(Gforce >= 7 || Gforce < 9)
which is equivalent to
if Gforce < 7 && Gforce >= 9
Are there any finite numbers which are simultaneously less than 7 and greater than or equal to 9? NO! And if the opposite of a test selects for nothing, it follows that the original test selects for everything finite.
5 -> is less than 9, so succeeds
8 -> is greater than 7 and also less than 9, so succeeds
11 -> is greater than 7, so succeeds
The only scalar numeric value for Gforce that would not pass the >=7 || < 9 test, is if Gforce is NaN.
else Gforce > 11
Notice you did not use elseif there, so as far as MATLAB is concerned, that section of code is equivalent to
else
Gforce > 11
with Gforce > 11 resulting in a logical computation whose result is displayed (because there is no semi-colon following it to tell it not to display), and whose value does not otherwise affect the outcome of the code.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by