Matlab OR | operator not working

16 views (last 30 days)
bsriv on 21 Feb 2019
Commented: Steven Lord on 22 Feb 2019
Hi I have a dataset ( of 90,000 or so indices with values at each index. I am trying to pull the indices at certain values 21009 and 21003
When I sum( I get 80, which is correct (ie, there are 80 indices with values of 21009). When I sum( I get 150, also expected.
However when I try to pull both sum( 21009 | 21003) I get 90,000 and when I look at the output for | 21003) it's just a column of 1s. It's probably something obvious but what am I missing?
  1 Comment
Stephen23 on 22 Feb 2019
Following the documented rules of operator precedence
the syntax that you invented 21009 | 21003
is equivalent to
( 21009) | 21003
which, because the term in the parentheses can be either false or true, is therefore equivalent either of these:
(false) | 21003
(true) | 21003
which, because any non-zero values is considered to be true, are equivalent to these:
(false) | true
(true) | true
which (using standard rules of logic) is clearly always true.

Sign in to comment.

Accepted Answer

Bob Thompson
Bob Thompson on 21 Feb 2019
To the best of my knowledge the or operator doesn't work quite like that. You need to set separate conditions on each side of the or, rather than multiple values to check for. == 21009 | == 21003;
Steven Lord
Steven Lord on 22 Feb 2019
If you later decide that you want to select elements that match any of a larger set of values (3, 4, or more) consider switching to ismember instead of chaining together 3, 4, or more expressions with the or operator | between them.

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!