3

If I want to ensure that an if statement only executes if BOTH of two conditions are true, should I be using & or && between the clauses of the statement?

For example, should I use

if a == 5 & b == 4

or

if a == 5 && b == 4

I understand that the former is elementwise and the latter is capable of short-circuiting but am not clear on what this means.

CaptainProg
  • 5,610
  • 23
  • 71
  • 116
  • 1
    The MATLAB documentation discusses operator short-circuiting [here](http://www.mathworks.co.uk/help/techdoc/matlab_prog/f0-40063.html#f0-39129), the `&&` and `||` operators [here](http://www.mathworks.co.uk/help/techdoc/ref/logicaloperatorsshortcircuit.html) and the element-wise operators `&` and `|` [here](http://www.mathworks.co.uk/help/techdoc/ref/logicaloperatorselementwise.html). – Chris Jan 21 '12 at 16:19

1 Answers1

5

For a scalar boolean condition I'd recommend you use &&. Short-circuiting means the second condition isn't evaluated if the first is false, but then you know the result is false anyway. Either & or && one will be true only if both sides of the expression are true, but & can return a matrix result if one of the operands is a matrix.

Also, I believe in Matlab comparisons should be done with ==, not with = (assignment).

sverre
  • 6,768
  • 2
  • 27
  • 35
  • Incidentally, why wouldn't you want an AND condition to short-circuit? Since it's only going to be true if all the conditions are true, surely if the first condition is evaluated and turns out to be false, evaluating more is just a waste of processing power..? – CaptainProg Jan 21 '12 at 16:18
  • @CaptainProg sometimes you want to evaluate functions for the side effects – sverre Jan 21 '12 at 16:19
  • Sverre, could you elaborate on this? – CaptainProg Jan 21 '12 at 16:25
  • @CaptainProg see http://stackoverflow.com/questions/1445867/why-would-a-language-not-use-short-circuit-evaluation – sverre Jan 21 '12 at 17:18