Boolean operator
In Matlab, there are four logical (boolean) operators:
Boolean operator:
Meaning:
&
Logical and
|
Logical or
~
Logical NOT (add-on)
xor
Exclusive or
These operators produce vectors or matrices of the same size as the operands, with 1 when the condition is true, and 0 when the condition is false.
Given x = array [0 7 3 5] and y = array [7 8 2 0], these are some possible operations:
Operation: Result:
n = x & yn = [1 0 0 1]
= ~ m (y | x) = m [0 0 0 0]
xor = p (x, y) p = [1 0 0 1]
Once the output logical Boolean operations or is a vector or matrix with only 0 or 1, the output can be used as the index of an array to extract the appropriate elements. For example, to see the elements of x which satisfy both conditions (x < y) and (x < 4), you can write x ((x < y) and (x < 4)).
Operation: Result:
x < y ans = [1 1 1 0]
x < 4 ans = [0 1 0 0]
q = x ((x < y) and (x < 4)) q = [0 3]
In addition to these Boolean operators, there are several useful built-in logical functions, such as:
any
True if any element of a vector is true
all
True if all elements of a vector are true
exist
true if the argument exists
isempty
true for an empty array
isinf
true for all infinite elements of an array
isNaN
true for all elements of an array that ara-number
find
find indexes of non-zero elements of an array
Relational operators
There are six relational operators in Matlab:
Relational operator:
Meaning:
<
less than
<=
less than or equal
>
greater than
> =
greater than or equal
==
equal (no assignment)
~ =
not equal
These operations result in a vector to array the same size as the operands, with 1 when the relationship is true, and 0 when it is false.
Data Arrays x = [3 5 0 7] and y = [0 2 8 7], these are some possible relational operations:
Operation: Result:
k = x < y k = [1 1 1 0]
k = x y = k < = [1 1 1 0]
k = x = y = k = [0 0 0 0]
Although these operations are typically used in conditional commands, such as if-else statements to branch to different cases, they can be used to make very complex array manipulation. For example x = y (y > 0.45) finds all the elements in the vector y such that y i > 0.45 and stores them in the vector x. These operations can be combined with Boolean operators, too.