Is this a MATLAB bug? (Logical expression)
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Jan
2022-3-25
编辑:Jan
2022-3-25
(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 个评论
Steven Lord
2022-3-25
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).
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!