while loop with else if statement
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Antworten (1)
Walter Roberson
am 19 Mär. 2021
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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!