if statement with greater than and less than
Show older comments
The following doesn't seem to be working as intended:
if 0 <= MBPosition <= 2*Delta ;
Even though MBPosition is within the range, the code moves to the "else" statement. What's the correct way to code this?
Accepted Answer
More Answers (1)
This is a common shorthand notation in mathematics, thus
A < B < C
where we know that what is really meant is a pair of tests, thus
(A < B) & (B < C)
The problem is, it fails in MATLAB, Why? When MATLAB executes a test, for example
5 < 7
the result will be a boolean value, thus 0 or 1. In this case, it is true, so we get a 1. So what happens when we write a chained test, as the common shorthand uses? For example...
5 < 7 < 2
Surely, that must be false. But MATLAB thinks it was true. Why? MATLAB works from left to right. It breaks that test down as if you had written:
(5 < 7) < 2
Again now, what is the result of 5<7? That is true, so it is 1. Is 1 < 2? Of course. So MATLAB thinks the chained conditional
(5 < 7 < 2) is actually a TRUE statement!
The point being, you cannot use chained conditions as you do in the common mathematics shorthand notation. Sorry, you cannot do so. You must write the chain as two separate conditions.
(A < B) & (B < C)
Better of course, is you really want to use the short-circuited operators, thus
(A < B) && (B < C)
This way the second fragment in that test will not be evaluated depending on the state of the first.
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!