Tutorial

Logical OR in MATLAB

The symbols | and || perform element-wise and short-circuited OR operations, respectively.

Preparation

Create two matrices using the following code:

A = [0, 1, 0; 1, 0, 1];
B = [1, 1, 0; 0, 0, 1];

Element-wise OR

A | B | … performs an element-wise OR of all input matrices A, B, etc.

% Element-wise OR of matrices A and B
R = A | B;
To learn how logical OR works, see Table 1.

All nonscalar input matrices must have the same size. If the logical expression contains both scalar and nonscalar inputs, the scalars are treated as if they were the same size as the other inputs.

Short-circuited OR

expr1 || expr2 performs a short-circuited OR. Both expr1 and expr2 must evaluate to a scalar logical result. It is called “short-circuited” because expr2 is not evaluated if expr1 is true.

% Short-circuited OR
i = 8;
outOfRange = (i < 0) || (i > 7);

Note: A true value in expr1 is enough to consider the entire OR operation as true (Table 1).

Truth table

A logical OR operation returns true if at least one operand is true, otherwise returns false (Table 1).

Table 1. Truth table of the logical OR operation.
A B A OR B
True True True
True False True
False True True
False False False

Note: By convention, zero is considered false and nonzero numbers are considered true.

Further reading

I recommend the following books to learn more on logical operations in MATLAB:

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. Chapters 4 and 5 explain selection statements and loops, two areas that extensively make use of logical operations.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The eighth chapter covers logical operations and selection statements.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc or;

Exercise

Consult the help documentation of the functions rand and sum. Use rand to create a matrix X of size 3×4. Calculate how many elements in X are not in the interval \([0.5,0.75]\).

Source code

I hope you have learned how to perform a logical OR in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.