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 AND of all input matrices
% Element-wise AND of matrices A and B R = A & B;
R = 0 1 0 0 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 AND. Both
expr2 must evaluate to a scalar logical result. It is called “short-circuited” because
expr2 is not evaluated if
% Short-circuited AND i = 8; inRange = (i >= 0) && (i <= 7);
inRange = 0
false value in
expr1 is enough to consider the entire AND operation as
false (Table 1).
A logical AND operation returns
true if all operands are
true, otherwise returns
false (Table 1).
|A||B||A AND 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 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 AND in MATLAB. The source code developed in this tutorial is available at this page.