Search code examples
matlaboctaveboolean-logicbitwise-and

What is the difference between & and && in octave?


Initially I had used a single &. However, Octave said to use a "MATLAB style short cut". So I changed to double &&. As you can see, the equality finder works with single & but not with &&:

find(node(:,1)==b && node(:,2)==ro)
  ans = [](0x0)
find(node(:,1)==b & node(:,2)==ro)
  ans =  6

Why aren't the two results equal?


Solution

  • The double logical operations, && and || are short-circuit operation.

    They have a very powerful use: They don't evaluate all the conditions. This is very useful for things like:

    if (a==5) && super_slow_computation_here()

    In the above case, if a is not equal to 5, super_slow_computation_here won't be even computed, it will "short circuit" the if condition, as we know it won't be true (and). With a single & it will compute both, then compute the and.

    Obviously this is not what you want, you want all the conditions computed, because you are calling find, you need all rows of your array used. So why does Octave suggest to use double? Because Octave is wrong. Octave sees you using 2 arrays and a logical operator and assumes that you are using them within an if and not find, so suggests that. Ignore Octave ;)