MATLAB provide two types of logical operators:
Element-wise − these operators operate/work on corresponding elements of logical arrays.
Short-circuit − these operators operate/work on scalar, logical expressions.
Element-wise logical operators operate by taking single element at a time of logical arrays. The symbols |, & and ~ are the logical array operators OR, AND, and NOT respectively.
Short-circuit logical operators do short-circuiting on logical operations. The symbols || and&& are the logical short-circuit operators OR and AND respectively.
These can be better understood by taking the following examples.
a = 5;
b = 20;
if ( a && b )
disp('Line 1 - Condition is true');
if ( a || b )
disp('Line 2 - Condition is true');
% lets change in the value of a and b
a = 0;
b = 10;
if ( a && b )
disp('Line 3 - Condition is true');
disp('Line 3 - Condition is not true');
if (~(a && b))
disp('Line 4 - Condition is true');
MATLAB always gives the (& ) operator preference over the | operator. Although MATLAB generally evaluates expressions from left to right, the expression a|b&c is solved as a|(b&c). It may be a good idea to use brackets to explicitly show the intended precedence of statements containing combinations of & and |.
These logical operators have the M-file function equivalents, as shown.
|Logical Operation||Equivalent Function|
|A & B||and(A,B)|
|A | B||or(A,B)|