Logical Operators

 

Logical operators (Short-Circuiting):

  • && : And
  • || : Or

Logical operators (Element-wise):

  • & : And
  • | : Or
  • ~ : Not

Logical exclusive-OR function:

  • xor

A && B
  • B is evaluated only if A is true
  • A and B can be scalars only
  • Use this when constructing conditional expressions for use in if, while, etc.
A & B
  • A and B both are evaluated
  • A and B can be scalars or vectors (element-wise fashion for vectors)
xor(A,B)
  • A and B can be scalars or vectors (element-wise fashion for vectors)

X = [1 0 0 1 1]
Y = [0 0 0 1 0]
X & Y
>>  0  0  0  1  0   % (1×5 logical array)
X && Y
>> [MATLAB] ERROR: operators must be convertible to logical scalars
>> [OCTAVE] 0
xor(X,Y)
>>  1  0  0  0  1   % (1×5 logical array)

X = [1; 0; 0; 1; 1]
Y = [0; 0; 0; 1; 0]
X & Y
>>  % (5x1 logical array)
  0
  0
  0
  1
  0
X && Y
>> [MATLAB] ERROR: operators must be convertible to logical scalars
>> [OCTAVE] 0

1 && 2
>> 1    % (logical)
1 && 0
>> 0
1 || 0
>> 1
1 & 2
>> 1    % (logical)
1 & 0
>> 0
1 | 0
>> 1
xor(1,0)
>> 1