Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between & and && in MATLAB?

What is the difference between the & and && logical operators in MATLAB?

like image 819
Fantomas Avatar asked Sep 04 '09 13:09

Fantomas


3 Answers

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

like image 182
Fraser Avatar answered Nov 11 '22 00:11

Fraser


&& and || take scalar inputs and short-circuit always. | and & take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.

See these doc pages for more information.

like image 40
Loren Avatar answered Nov 11 '22 00:11

Loren


As already mentioned by others, & is a logical AND operator and && is a short-circuit AND operator. They differ in how the operands are evaluated as well as whether or not they operate on arrays or scalars:

  • & (AND operator) and | (OR operator) can operate on arrays in an element-wise fashion.
  • && and || are short-circuit versions for which the second operand is evaluated only when the result is not fully determined by the first operand. These can only operate on scalars, not arrays.
like image 18
gnovice Avatar answered Nov 11 '22 01:11

gnovice