Sometimes the result of a calculation produces an entire numeric or
logical array when you need only a single logical true
or
false
value. In this case, use the any
or
all
functions to reduce the array to a single scalar logical for
further computations.
The any
and all
functions are natural extensions
of the logical |
(OR) and &
(AND) operators,
respectively. However, rather than comparing just two elements, the any
and all
functions compare all of the elements in a particular dimension
of an array. It is as if all of those elements are connected by &
or |
operators and the any
or all
functions evaluate the resulting long logical expression(s). Therefore, unlike the core
logical operators, the any
and all
functions reduce
the size of the array dimension that they operate on so that it has size 1. This enables
the reduction of many logical values into a single logical condition.
First, create a matrix, A
, that contains random integers between 1
and 25.
rng(0) A = randi(25,5)
A = 21 3 4 4 17 23 7 25 11 1 4 14 24 23 22 23 24 13 20 24 16 25 21 24 17
Next, use the mod
function along with the logical NOT operator,
~
, to determine which elements in A
are even.
A = ~mod(A,2)
A = 0 0 1 1 0 0 0 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 0 1 0
The resulting matrices have values of logical 1
(true
) where an element is even, and logical 0
(false
) where an element is odd.
Since the any
and all
functions reduce the
dimension that they operate on to size 1, it normally takes two applications of one of the
functions to reduce a 2–D matrix into a single logical condition, such as
any(any(A))
. However, if you use the notation A(:)
to regard all of the elements of A
as a single column vector, you can use
any(A(:))
to get the same logical information without nesting the
function calls.
Determine if any elements in A
are even.
any(A(:))
ans = 1
The result is logical 1
(true
).
You can perform logical and relational comparisons within the function call to
any
or all
. This makes it easy to quickly test an
array for a variety of properties.
Determine if all elements in A
are odd.
all(~A(:))
ans = 0
The result is logical 0
(false
).
Determine whether any main or super diagonal elements in A
are
even.
any(diag(A) | diag(A,1))
Error using | Inputs must have the same size.
MATLAB® returns an error since the vectors returned by diag(A)
and
diag(A,1)
are not the same size.
To reduce each diagonal to a single scalar logical condition and allow logical
short-circuiting, use the any
function on each side of the short-circuit
OR operator, ||
.
any(diag(A)) || any(diag(A,1))
ans = 1
The result is logical 1
(true
). It no longer
matters that diag(A)
and diag(A,1)
are not the same
size.
Logical Operators: Short Circuit
| all
| and
| any
| or
| xor