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 

Related Posts

  • Look for the loopLook for the loop
    A very well known piece of knowledge is that Matlab is bad at for loop. But you might ask: why? ...
  • Columns and Rows are not the sameColumns and Rows are not the same
    I am going to talk about arrays today..I show that Columns and Rows are not the same. I end on a ...
  • Copy on WriteCopy on Write
    Since I was recently talking about Pointers in Matlab, I thought I should make this picture compl...
  • Inline your linesInline your lines
    In essence, writing a Matlab program is aligning a succession of command that you send to the Mat...
  • Preallocation is not an optionPreallocation is not an option
    As any activity, programming does require that you follow some rules of good practice. In this po...
This entry was posted in Intermediate, Optimizing your code. Bookmark the permalink.

Leave a Reply