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.

example

Examples

collapse all

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

collapse all

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

collapse all

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:

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

Extended Capabilities

Version History

Introduced before R2006a