Is this a MATLAB bug? (Logical expression)
1 view (last 30 days)
Show older comments
Hello,
I have just found something that I really don't understand...
Say I have a variable called x1 which has a value of 1, and a variable x2 which has a value of 2.
Now, if I logically say "x1 or x2 is greater than 1", I should get 1, as x2 is indeed greater than 1.
And if I type this:
x1 = 1;
x2 = 2;
x1|x2>1
I get a logical "1" as answer, as expected.
However it would seem to me that writing this would yield exactly the same result, as I just add some parenthesis:
x1 = 1;
x2 = 2;
(x1|x2)>1
But instead I get a logical "0" here. What am I missing? Why are the answers different from each other?
Thank you!
0 Comments
Accepted Answer
Jan
on 25 Mar 2022
Edited: Jan
on 25 Mar 2022
(x1 | x2) is TRUE, if at least one of them is not zero. If both are zero, FALSE is replied. In the next step TRUE is converted to 1 and FALSE to 0. Neither 1 nor 0 is greater than 1, so the expression (x1 | x2) > 1 replies FALSE as expected.
Your expression "x1 or x2 is greater than 1" means something else:
(x1 > 1) | (x2 > 1)
You can combine this in English, but not in Matlab or other similar programming languages.
The different between "x1 | x2 > 1" and "(x1 | x2) > 1" is the precedence order. In the first one, the > operator has a higher precedence than the | , so X2 > 1 is evaluated at first. Then you get x1 | FALSE, which is TRUE, because x1 is not zero.
1 Comment
Steven Lord
on 25 Mar 2022
To put it another way, the expressions x1 | x2 > 1 and (x1 | x2) > 1 are not equivalent. The expressions x1 | x2 > 1 and x1 | (x2 > 1) are equivalent. Jan correctly wrote out the expression equivalent to the intent of your English description, (x1 > 1) | (x2 > 1).
More Answers (0)
See Also
Categories
Find more on Logical 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!