For more information, visit: http://matrixlab-examples.com/boolean-operator.html
AND, OR, NOT, XOR
Boolean and relational operators are explained so as to be used in Matlab, Freemat and other programming languages. Specific examples are given.
2. 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
3. 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 2 Result of
Condition 1 & Condition 2
0 0 0
0 1 0
1 0 0
1 1 1
4. 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]
5. 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 2 Result of
Condition 1 | Condition 2
0 0 0
0 1 1
1 0 1
1 1 1
6. 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]
7. 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.
Condition Result of
~ Condition
0 1
1 0
8. Boolean Operators
The ~ (NOT) logical operator
Example in Matlab:
a = [0 1];
b = ~a
Produces:
b = [1 0]
9. 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 B Result of
xor(A, B)
0 0 0
0 1 1
1 0 1
1 1 0
10. 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]
11. 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
12. 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]
then
If 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]
13. 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]
14. Boolean Operators
For more examples and details, visit:
matrixlab-examples.com/boolean-operator.html