MATLAB Understanding the Differences Between & and && Operators in MATLAB

  • Thread starter Thread starter gfd43tg
  • Start date Start date
  • Tags Tags
    Matlab
Click For Summary
The discussion clarifies the differences between the & and && operators in MATLAB. The & operator performs elementwise logical AND on matrices, while the && operator is a short-circuited logical AND that only evaluates subsequent expressions if the preceding ones are true. This means that in an expression like A && B && C && D, if A is false, MATLAB will not evaluate B, C, or D, potentially improving performance. In contrast, A & B & C & D evaluates all components regardless of the truth value of A. Understanding these distinctions is crucial for optimizing code and managing logical operations effectively in MATLAB.
gfd43tg
Gold Member
Messages
947
Reaction score
48
Hello,

I am having some difficulties understanding the difference between the two and when I would want to use one over the other.
 
Physics news on Phys.org
in java & represents bitwise anding 000&111 = 000 vs 010&011 = 010 ...

whereas && represents logical anding where you have two boolean expressions A and B then A&&B will be true only if A is true and B is true.
 
In MATLAB, & is the logical elementwise AND operation for matrices.

&& is a short-circuited logical AND operator.

The short-circuited operators && and || can be quicker than & and | in expressions where the evaluation can end early. For example consider the expression
Code:
A && B && C && D
which evaluates to TRUE only if A, B, C, and D are all TRUE. If A is FALSE, then MATLAB will not even evaluate B, C, or D. However, in the expression
Code:
A & B & C & D
MATLAB will always evaluate A, B, C, and D to determine the result of the expression.
 
Last edited:
  • Like
Likes 1 person

Similar threads

  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 4 ·
Replies
4
Views
4K
Replies
6
Views
4K
  • · Replies 32 ·
2
Replies
32
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K