while loop with else if statement

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