views:

1112

answers:

6

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

+9  A: 

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)

Fraser
Fraser
gnovice
+1 on the scalar/array addition.
Fraser
+2  A: 

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here: http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/f16-6011.html&http%3A//www.mathworks.com/products/matlab/

And

http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/f16-6011.html&http%3A//www.mathworks.com/products/matlab/

Mark
+1  A: 

&& and || are short circuit operators operating on scalaras. & and | always evaluate both operands and operate on arrays.

Dima
+2  A: 

Similar to other languages, '&' is a logical bitwise operator, while '&&' is a logical operation.

For example (pardon my syntax).

If A = [True True False True] B = False

A & B = [False False False False]

..or if B = True A & B = [True True False True]

For '&&', the right operand is only calculated if the left operand is true, and the result is a single boolean value.

x = (b ~= 0) && (a/b > 18.5)

Hope that's clear.

eskerber
+1  A: 

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.
gnovice
+1  A: 

&& 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: http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorselementwise.html?BB=1 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorselementwise.html?BB=1

--Loren

Loren
gnovice

related questions