Short-Circuit OR - Logical OR with short-circuiting - MATLAB (original) (raw)
Main Content
Logical OR with short-circuiting
Syntax
Description
[expr1](#mw%5Fdbc18457-05c7-4280-8662-86e8f0cc1ad6) || [expr2](#mw%5Fdbc18457-05c7-4280-8662-86e8f0cc1ad6)
represents a logical OR
operation that employs Logical Short-Circuiting behavior. That is, expr2
is not evaluated if expr1
is logical 1
(true
). Each expression must evaluate to a scalar logical result.
Examples
Create two vectors.
X = [1 0 0 1 1]; Y = [0 0 0 0 0];
Using the short-circuit OR operator with X
and Y
returns an error. The short-circuit operators operate only with scalar logical conditions.
Use the any
and all
functions to reduce each vector to a single logical condition.
The expression is equivalent to 1 OR 0
, so it evaluates to logical 1
(true
) after computing only the first condition, any(X)
.
Input Arguments
Logical expressions, specified as any valid MATLABĀ® expressions that evaluate to logical scalars.
Example: isscalar(x) || isvector(x)
Example: (x > 1) || (x < -1)
Data Types: logical
More About
With logical short-circuiting, the evaluation of logical expressions can terminate early once the result becomes fully determined. Due to the properties of logical AND and OR, the result of a logical expression is sometimes fully determined before evaluating all of the conditions:
- The logical
and
operator returns logical0
(false
) if even a single condition in the expression is false. - The logical
or
operator returns logical1
(true
) if even a single condition in the expression is true.
When the evaluation of a logical expression terminates early by encountering one of these values, the expression is said to have short-circuited. Used properly, this technique enables you to perform complex comparisons efficiently in your code.
For example, in the expression A && B
, MATLAB does not evaluate condition B
at all if condition A
is false. Once it is determined that A
is false, the value of B
cannot change the outcome of the operation.
Tips
- When you use the element-wise
&
and|
operators in the context of anif
orwhile
loop expression (and only in that context), they use short-circuiting to evaluate expressions.
However, you should always use the&&
and||
operators to enable short-circuit evaluation. Using the&
and|
operators for short-circuiting can yield unexpected results when the expressions do not evaluate to logical scalars.
Extended Capabilities
Version History
Introduced before R2006a