Main Content

Short-Circuit OR, ||

Logical OR with short-circuiting

Description

expr1 || expr2 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.

any(X) || all(Y)
ans = logical
   1

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

Tips

  • When you use the element-wise & and | operators in the context of an if or while 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

expand all

Version History

Introduced before R2006a