What’s the difference between AND and AND AND?

I guess most of you know what & means. This is the AND operator. It does something simple. If you have two variable x and y and you ask :

a=(x==2) & (y==3)

Then a will be equal to 1 only if both x is equal to 2 and y is equal to 3. Otherwise a is 0.

This is very basic programming. So I am not going to develop on this for today.

But I am sure you came across this && operator. Sometimes even Matlab tells you that && is better than &… I am sure some of you have used it but don’t know what it is.  Yes, don’t lie to me, I know, I did the same thing…

a=(x==2) && (y==3)

What is happening here?

Actually & and && are quite different things.

& is a classical element-wise operator, it can operate on both matrices (provided that they are of the same size) and scalars. This is the AND you know back from school when you were probably learning electronic.

&& is a funny thing. Actually it ONLY work with scalar. In ‘a && b’, a and b can’t be matrices, even if there are of the same size. && is a short-circuit operator. This means that in ‘a && b’, b is going to be evaluated only if it is NEEDED to evaluate the whole expression, the calculation can be “short-circuited” to only evaluating a if b is not needed. When does this happen?

Well, simply speaking, if a is 0, then a && b is by definition also 0 so you don’t need to evaluate b. If a is 1, well, then you need to know b to have the final result.

This can very useful in some cases :

  • The calculation of both a and b is long, so you don’t want to wait for b if a already tell you the answear.
  • Calculating b can give you an error if a is 0. For instance if you check for the existence of a variable in a and then you compare the value of this variable with something in b.

I won’t talk about OR OR or ||, I think you got the idea.
Take some time to revise the corresponding matlab page :

http://www.mathworks.com/help/techdoc/ref/logicaloperatorsshortcircuit.html 

This entry was posted in Intermediate, Optimizing your code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *