Boolean Operators
In Matlab
Boolean Operators
You use logical operators in conditional expressions much as you use math operators in numeric expressions.
SYMBOL in Matlab
MEANING
& logical AND operator
| logical OR operator
~ logical NOT (complement)
xor exclusive-OR
Boolean Operators
The & (AND) logical operator
The & operator lets you specify multiple conditions that must be true before an action can be taken.
Condition 1 Condition 2Result of
Condition 1 & Condition 2
0 0 0
0 1 0
1 0 0
1 1 1
Boolean Operators
The & (AND) logical operator
Example in Matlab:
a = [0 0 1 1];b = [0 1 0 1];
c = a & b
Produces: c = [0 0 0 1]
Boolean Operators
The | (OR) logical operator
The | operator lets you create a more flexible set of conditions that must be met before an action can take place.
Condition 1 Condition 2Result of
Condition 1 | Condition 2
0 0 0
0 1 1
1 0 1
1 1 1
Boolean Operators
The | (OR) logical operator
Example in Matlab:
a = [0 0 1 1];b = [0 1 0 1];
c = a | b
Produces: c = [0 1 1 1]
Boolean Operators
The ~ (NOT) logical operator
The ~ operator lets you negate a condition: if a condition is false, the NOT operator makes the condition true; if a condition is true, NOT makes it false.
ConditionResult of
~ Condition
0 1
1 0
Boolean Operators
The ~ (NOT) logical operator
Example in Matlab:
a = [0 1];
b = ~a
Produces: b = [1 0]
Boolean Operators
The xor (logical exclusive-OR)
C = xor(A, B) performs an exclusive-OR operation on the corresponding elements of arrays A and B.
A BResult of xor(A, B)
0 0 0
0 1 1
1 0 1
1 1 0
Boolean Operators
The xor logical operator
Example in Matlab:
a = [0 0 1 1];b = [0 1 0 1];
c = xor(a, b)
Produces: c = [0 1 1 0]
Relational Operators
There are six relational operators in Matlab:
Symbol Meaning
< less than
<= less than or equal
> lreater than
>= greater than or equal
== equal
~= not equal
Relational Operators
These operations result in a vector or matrix of the same size as the operands, with 1 where the relation is true and 0 where it’s false.
Example:
If x = [2 5 3 9]y = [0 2 8 9]
thenIf we type… We’ll get…
a = x < y a = [0 0 1 0]
a = x <= y a = [0 0 1 1]
a = x > y a = [1 1 0 0]
a = x >= y a = [1 1 0 1]
Relational and Boolean Operators
Naturally, we can combine relational and boolean operators to create sophisticated manipulations.
For example, if we have vector x = -5 : 10 and we want to find all the elements that are only within the interval -3 < x ≤ 2, we can find them like this:
y = x(-3 < x & x <= 2)
and we get:y = [-2 -1 0 1 2]
Boolean Operators
For more examples and details, visit:
matrixlab-examples.com/boolean-operator.html