Pregunta

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.

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top