Why is Answer to 3 < A < 7 Unexpected?
There have been countless (not really!) times on the MATLAB newsgroup where a question of the sort written in the title has been asked (and answered). Let's go through the code to understand what's happening.
DISCLAIMER: It's not my intention in this post to discuss non-scalar behavior.
As part of program, suppose we need to see if some value lies between two others. let's say A is the value we are checking at the limits are low=3 and high=7.
low = 3; high = 7;
Mathematically you might write this as
low < A < high
Let's try that for A values both inside the range and outside to start. And let me place the expression into an anonymous function so I don't have to keep repeating it.
myExpr = @(x) low < x < high; inResult = myExpr(pi) outResult = myExpr(17)
inResult = 1 outResult = 1
It can't be true that both pi and 17 lie between 3 and 7. So what's going on? Let's dissect the expression.
First Part of Expression: low < A
Let's look at the first part of the expression.
step1In = low < pi step1Out = low < 17
step1In = 1 step1Out = 1
and we see that this is true for both of our inputs.
Second Part of Expression: previous output < high
The second part of our expression uses the output from the first expression and continues from there.
step2In = step1In < high step2Out = step1Out < high
step2In = 1 step2Out = 1
and we see that we get ones, or true, for both of these. What's going on?
Look at the Types
Name Size Bytes Class Attributes step1In 1x1 1 logical step1Out 1x1 1 logical
The results from step 1 are logical - are these numbers greater than low? And the answers for both of our values is yes, or true, represented in MATLAB as logical values. When we take these values as inputs in the second step, what happens is the true values are interpreted as numeric inputs with value 1. And then we ask if 1 is less than high. Which it is in both of these cases!
How to Get the Expected Answer
How do we get the expected answer, and it's easy. We simply combine two logical expressions, but in a different way than above.
myExprCorrect = @(x) (low < x) & (x < high) inResult1 = myExprCorrect(pi) outResult1 = myExprCorrect(17)
myExprCorrect = @(x)(low<x)&(x<high) inResult1 = 1 outResult1 = 0
What we did is checked first to see if the number was greater than low and separately checked the same number with high. After getting two logical answers, we combine them. They must both be true for numbers that lie between low and high and hence the result should yield true only under those conditions.
For what it's worth, I always use parentheses to group my expressions to make them very readable for me so I don't need to wonder later what I intended to be testing.
Have Compound Expressions Caused You Problems?
Let me know here if you've had trouble with expressions like the one in this post.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.