Understanding the Differences Between & and && Operators in MATLAB

  • Context: MATLAB 
  • Thread starter Thread starter gfd43tg
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 9K views
gfd43tg
Gold Member
Messages
949
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   Reactions: 1 person