while loop with else if statement
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Walter Roberson
el 19 de Mzo. de 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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!