How exactly does 'OR' logic works in Matlab. Getting Wrong answers.

조회 수: 1 (최근 30일)
Riyasat
Riyasat 2015년 12월 20일
편집: Stephen23 2015년 12월 21일
How can the following be true?? The single and the double bar gives the following as true, but it's clearly wrong... What am I missing?
>> 'D' == 'A' | 'C' | 'I'
ans =
1
>> 'D'=='A'||'C'||'I'
ans =
1
  댓글 수: 2
Jan
Jan 2015년 12월 21일
The answer is clearly correct, only the expectation is wrong.
Stephen23
Stephen23 2015년 12월 21일
It seems that people forget about operator precedence as soon as they leave high school.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2015년 12월 20일
'D' == 'A' | 'D' == 'C' | 'D' == 'I'
ismember('D', {'A', 'C', 'I'})
  댓글 수: 1
Walter Roberson
Walter Roberson 2015년 12월 21일
편집: Stephen23 2015년 12월 21일
To expand:
The MATLAB comparison operators have higher priority than the "|" and "||" and "&" and "&&" operators. The expression
'D' == 'A' | 'C' | 'I'
that would be evaluated as
('D' == 'A') | ('C') | ('I')
The ('D' == 'A') part would be false. The ('C') part is the same as the implicit test ('C' ~= 0) and so that is true. or(false,true) is true so the expression as a whole becomes true.
The MATLAB comparison and logical operators never have implicit "chains". It is not correct in MATLAB to write
'D' == 'A' | 'C' | 'I'
with the expectation that 'D' will be tested against 'A' or 'C' or 'I' .
The MATLAB comparison and logical operators are vectorized. You can write
'D' == ['A', 'C', 'I']
which would evaluate to [false, false, false] . However, if you had this in an "if" condition then the test would be equivalent to
'D' == 'A' & 'D' == 'C' & 'D' == 'I'
which would have to be false because no value can simultaneously be equal to three values. In an "if" condition, the result is not considered true unless all of the values in the logical condition are considered true, the equivalent of
all('D' == ['A', 'C', 'I'])
To get the equivalent of testing to see if at least one of them holds you should specifically code a call to any()
any('D' == ['A', 'C', 'I'])
You might have noticed that ['A', 'C', 'I'] is the same as 'ACI' so yes the above line of code is the same as
any('D' == 'ACI')
Remember, in MATLAB strings are exactly the same as row vectors of characters and all of the row vector operations apply, same as if you had tested
any(4 == [1 3 9])
If you want to treat a string as a single object instead of as a row vector of characters, you need to use strcmp()
strcmp('D', 'A') | strcmp('D', 'C') | strcmp('D', 'I')
or in short form
strcmp('D', {'A', 'C', 'I'})
Here {'A', 'C', 'I'} is not the same as ['A', 'C', 'I'] and so is not the same as 'ACI'
Personally I am more likely to code with ismember() than with strcmp()
ismember('D', {'A', 'C', 'I'})

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by