Is this a MATLAB bug? (Logical expression)

1 回表示 (過去 30 日間)
Andrea Angella
Andrea Angella 2022 年 3 月 25 日
コメント済み: Steven Lord 2022 年 3 月 25 日
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!

採用された回答

Jan
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
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 ExchangeLogical についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by