Short-Circuit OR, ||
Logical OR with short-circuiting
OR operation that employs Logical Short-Circuiting behavior. That is,
expr2 is not evaluated if
true). Each expression must evaluate to
a scalar logical result.
Use Scalar Logical Conditions
Create two vectors.
X = [1 0 0 1 1]; Y = [0 0 0 0 0];
Using the short-circuit OR operator with
Y returns an error. The short-circuit operators operate only with scalar logical conditions.
all functions to reduce each vector to a single logical condition.
any(X) || all(Y)
ans = logical 1
The expression is equivalent to
1 OR 0, so it evaluates to logical
true) after computing only the first condition,
expr2 — Logical expressions
Logical expressions, specified as any valid MATLAB® expressions that evaluate to logical scalars.
isscalar(x) || isvector(x)
(x > 1) || (x < -1)
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:
andoperator returns logical
false) if even a single condition in the expression is false.
oroperator returns logical
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.
When you use the element-wise
|operators in the context of an
whileloop expression (and only in that context), they use short-circuiting to evaluate expressions.
However, you should always use the
||operators to enable short-circuit evaluation. Using the
|operators for short-circuiting can yield unexpected results when the expressions do not evaluate to logical scalars.
Run code in the background using MATLAB®
backgroundPool or accelerate code with Parallel Computing Toolbox™
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Introduced before R2006a
Short-Circuit AND |