フィルターのクリア

Can I Always Change the Order of Operands of Logical Operators?

2 ビュー (過去 30 日間)
Rightia Rollmann
Rightia Rollmann 2016 年 8 月 16 日
編集済み: James Tursa 2016 年 8 月 16 日
Is there any case that writing the operands of logical operators with different order make a different result? (A = B and B = A are totally different and not interchangeable)
Are A == B and B == A always the same?
Are A >= B and B =< A always the same?

回答 (3 件)

Star Strider
Star Strider 2016 年 8 月 16 日
Yes. They’re commutative.

Sean de Wolski
Sean de Wolski 2016 年 8 月 16 日
編集済み: Sean de Wolski 2016 年 8 月 16 日
Yes, with the exception of short circuiting behavior with || and &&. In which case the second expression may not run.

James Tursa
James Tursa 2016 年 8 月 16 日
編集済み: James Tursa 2016 年 8 月 16 日
(Semantics, == and >= and <= are "relational" operators, not "logical" operators. E.g. & and | are "logical" operators.)
For the built-in numeric and logical and char types, I can think of no situation where your relational examples would give a different result ... even when considering inf and NaN situations. But for OOP classes, of course, the behavior could be different depending on how the underlying overloaded code is written. E.g., if the < operator was coded to be the complement of the >= operator, you could get some unexpected results that were not the same:
>> A = 5;
>> B = 6;
>> A < B
ans =
1
>> B > A
ans =
1
>> ~(A >= B)
ans =
1 <-- Same result as A < B
>> A = inf
A =
Inf
>> B = NaN
B =
NaN
>> A < B
ans =
0
>> B > A
ans =
0
>> ~(A >= B)
ans =
1 <-- NOT the same result as A < B

カテゴリ

Help Center および File ExchangeData Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by