110

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

horchler
  • 18,384
  • 4
  • 37
  • 73
Fantomas
  • 1,495
  • 4
  • 12
  • 21

7 Answers7

104

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
  • 15,275
  • 8
  • 53
  • 104
  • 84
    On caveat: `&` can operate on arrays but `&&` can only operate on scalars. – gnovice Sep 04 '09 at 14:41
  • Side note: after 15 years working with Matlab almost daily I always use '&' and it has never bitten me in the ass. OTOH, I know many people who get annoyed using '&&' because they have to remember it isn't universal (yes I realize that '&' isn't as efficient because it doesn't short circuit but I pretty much never daisy-chain my operands so the savings nowadays are negligible). – eric Oct 03 '16 at 17:50
  • 7
    @neuronet it isn't really about efficiency, more that it permits a construct where the first expression guarantees a condition without which the second expression may cause a run-time error. e.g. `d != 0 && 1/d` vs `d !=0 & 1/d` - the first guarantees no division by zero, the second doesn't. – Fraser Nov 14 '16 at 17:06
  • Be warned! `&` and `|` _do_ short-circuit, sometimes. [Quoth the documentation](https://www.mathworks.com/help/matlab/ref/logicaloperatorsshortcircuit.html): "When you use the element-wise `&` and `|` operators in the context of an `if` or `while` loop expression (and _only_ in that context), they use short-circuiting to evaluate expressions." This bizarre behavior is peculiar to MATLAB and is not shared by any other language that uses these operators. – Aaron Rotenberg Dec 17 '18 at 20:07
  • 4
    This answer is incomplete and inaccurate. `&` does short-circuit if in an `if` statement. And `&&` takes scalar inputs. [@Loren's answer below](https://stackoverflow.com/a/1393606/7328782) is correct. – Cris Luengo Feb 15 '19 at 06:15
  • 3
    Also note that Loren is a MathWorks employee. An answer doesn't get more authoritative than that. If you're willing to make a sacrifice you could flag your answer for a mod to delete it (you can't delete it yourself, because it's accepted). You would keep the rep you gained from it (if I understand the system correctly), and we'd end up with a technically correct and authoritative top answer. – Andras Deak -- Слава Україні Feb 15 '19 at 12:05
40

&& 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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Loren
  • 1,725
  • 14
  • 6
  • 1
    Do you have any information on which Matlab versions shortcut `&` and `|` in if/while statements? It does not seem to be the case in R2012b and R2014a. – Tim Jan 22 '15 at 08:43
  • @Loren any idea *why* they designed one to work with scalars only? It seems strange... – eric Mar 23 '15 at 14:37
  • @neuronet: You cannot short-circuit if you operate on arrays. – Cris Luengo Feb 19 '19 at 21:07
18

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.
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
gnovice
  • 125,304
  • 15
  • 256
  • 359
9

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.

gnovice
  • 125,304
  • 15
  • 256
  • 359
Mark
  • 106,305
  • 20
  • 172
  • 230
7

& is a logical elementwise operator, while && is a logical short-circuiting operator (which can only operate on scalars).

For example (pardon my syntax).

If..

A = [True True False True]
B = False
A & B = [False False False False]

..or..

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.

Erik Kerber
  • 5,646
  • 7
  • 38
  • 56
  • 4
    It's not bitwise, it's element-wise. – Cris Luengo Feb 15 '19 at 06:19
  • 3
    Did I just get well-actually'd 10 years later? – Erik Kerber Feb 15 '19 at 16:50
  • 1
    Well, this question has gotten ~115k views so far, which means a lot of people have read misinformation here. Many of these answers are incomplete or contain wrong information. All you need to do is fix your answer or delete it. BTW: `bitand` is the bitwise logical AND operator in MATLAB. – Cris Luengo Feb 15 '19 at 17:13
4

&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if or while loop expressions.

Dima
  • 38,860
  • 14
  • 75
  • 115
2

A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...

  1. As others have mentioned, the short-circuiting behavior of &&/|| is similar to most C-like languages. That similarity / familiarity is generally considered a point in its favor.
  2. Using the && or || forms forces you to write the full code for deciding your intent for vector arguments. When a = [1 0 0 1] and b = [0 1 0 1], is a&b true or false? I can't remember the rules for MATLAB's &, can you? Most people can't. On the other hand, if you use && or ||, you're FORCED to write the code "in full" to resolve the condition.

Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
  • 1
    +1, but it should be noted that your answer only applies to cases where you **want** the final result of the operation to be scalar. There are many uses for & and | where && and || are useless because they can't return arrays, for example when doing fancy indexing like "selecting all r between 1 and 2: `r((r<2)&(r<2))`". – Jonas Heidelberg Aug 22 '11 at 22:01
  • Good point, Jonas. I was thinking of conditionals, not "logical indexing," (the MATLAB term for the "fancy indexing" you mentioned) when I wrote this. I changed the first sentence of my post to reflect that. Thanks for the reminder! – Bob Gilmore Aug 25 '11 at 05:42