Create two matrices using the following code:
A = [0, 1, 0; 1, 0, 1]; B = [1, 1, 0; 0, 0, 1];
A = 0 1 0 1 0 1
B = 1 1 0 0 0 1
A | B | … performs an element-wise OR of all input matrices
% Element-wise OR of matrices A and B R = A | B;
R = 1 1 0 1 0 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.
expr1 || expr2 performs a short-circuited OR. Both
expr2 must evaluate to a scalar logical result. It is called “short-circuited” because
expr2 is not evaluated if
% Short-circuited OR i = 8; outOfRange = (i < 0) || (i > 7);
outOfRange = 1
true value in
expr1 is enough to consider the entire OR operation as
true (Table 1).
A logical OR operation returns
true if at least one operand is
true, otherwise returns
false (Table 1).
|A||B||A OR B|
Note: By convention, zero is considered
false and nonzero numbers are considered
I recommend the following books to learn more on logical operations in MATLAB:
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.
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.
Consult the help documentation of the functions
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]\).
A possible solution could be:
X = rand(3,4); R = (X < 0.5) | (X > 0.75); count = sum(R(:));
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.