MATLAB Comparing '==' and 'or': True or False?

  • Thread starter Thread starter brydustin
  • Start date Start date
AI Thread Summary
Combining '==' with logical 'or' can yield results of True (1) or False (0) based on operator precedence and notation used. The evaluation of expressions like "3 == 4|5" and "3 == 4||5" shows that they are processed left to right, with '|' having lower precedence than '=='. The correct interpretation of "3 == (4|5)" results in 0, highlighting the importance of understanding operator precedence in MATLAB. The discussion emphasizes the need to clarify notation and precedence when using logical operators to avoid confusion. Understanding these principles is crucial for accurate coding and debugging in MATLAB.
brydustin
Messages
201
Reaction score
0
It seems as if combining == with logical or will always give True (1) or False (2) whenever you perform the simple check, its result is only dependent on choice of notation or(A,B) versus A||B (or A|B which is better for arrays, generally || is for single elements)

Is there something wrong? or am I totally missing something, thanks...

(source for equivalent notation: http://www.mathworks.co.uk/help/techdoc/ref/logicaloperatorselementwise.html)


>> 3 == 4|5

ans =

1

>> 3 == 4||5

ans =

1

>> 3 == 3||3

ans =

1

>> 3 == or(3,3)

ans =

0


>> 3 == or(-Inf,4)

ans =

0

>> 3 == or(2,3)

ans =

0
 
Physics news on Phys.org
[strike]It appears that 3 == 4|5 is simply evaluated left to right without precedence as (3 == 4)|5[/strike]

Correction: 3 == 4|5 is evaluated with the operator precedence shown below. (Same end result as above of course, "|" processed after "==").
 
Last edited:
yeah, cool... my bad

>> 3 == (4|5)

ans =

0
 
From the Matlab documentation the operator precedence is as follows.

Operators are shown in this list, ordered from highest precedence level to lowest precedence level:

1. Parentheses ()

2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^)

3. Unary plus (+), unary minus (-), logical negation (~)

4. Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\)

5. Addition (+), subtraction (-)

6. Colon operator (:)

7. Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=)

8. Element-wise AND (&)

9. Element-wise OR (|)

10. Short-circuit AND (&&)

11. Short-circuit OR (||)
 

Similar threads

Replies
5
Views
2K
Replies
2
Views
3K
Replies
6
Views
2K
Replies
14
Views
2K
Replies
4
Views
1K
Replies
2
Views
1K
Replies
6
Views
2K
Back
Top