MATLAB Answers

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

3 views (last 30 days)
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 Comments

Jan
Jan on 21 Dec 2015
The answer is clearly correct, only the expectation is wrong.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 20 Dec 2015
'D' == 'A' | 'D' == 'C' | 'D' == 'I'
ismember('D', {'A', 'C', 'I'})

  1 Comment

Walter Roberson
Walter Roberson on 21 Dec 2015
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'})

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!