Search code examples
matlabsyntaxshort-circuitinglogical-and

Why does this if statement give an output despite the && conditions not being satisfied?


I have been trying to execute a piece of code with some if conditions. This is a simple version of it.

X=100;Y=100;
if ((((X+1) && (Y+1))<=99) && (((X+1) && (Y+1))<=102))
    disp(X);
end

Despite both X and Y not satisfying the first condition, I still get the output as 100. I have tried all combinations of & and && to make the and operations in the work. I checked the difference between the two and I found that & is a logical bit-wise operator while && is a short-circuit operator, which probably doesn't change much in this context. What's the error with this syntax?

Of course the code works when I do this:

X=100;Y=100;
if (X+1)<=99 && (Y+1)<=99 && (((X+1) && (Y+1))<=102)
    disp(X);
end

But this is so inefficient when there are lot of conditions and each sub-condition must include the constraints. I'm sure this must be answered somewhere and this question might be a duplicate, so please point me to the answer.


Solution

  • So it looks like you understand what (X+1)<=99 && (Y+1)<=99 does. Let's look at ((X+1) && (Y+1))<=99:

    && requires a logical value on each side. a && b will turn a and b into logicals, effectively becoming a~=0 && b~=0. Thus:

    ((X+1)    && (Y+1)   ) <= 99
    ((X+1)~=0 && (Y+1)~=0) <= 99
    ( true    &&  true   ) <= 99
               1           <= 99
                          true
    

    Of course the truth value of (X+1)~=0 and (Y+1)~=0 could be different, but here you see this. In MATLAB, true is equal to 1 in a non-logical context, as when compared to 99.


    If you want to simplify this expression, use max instead of &&:

    X=100;Y=100;
    if max(X+1,Y+1)<=99 && max(X+1,Y+1)<=102
        disp(X);
    end
    

    If the max of a and b is smaller than 99, then both a and b are smaller than 99.

    (Obviously, the statement can be further simplified to if max(X+1,Y+1)<=102, since if the second inequality holds than so must the first.)