Experiment 5 Relational and Logical Operation
Experiment 5 Relational and Logical Operation
______________________________________________________________________________________________
Experiment No. 5
Relational and Logical Operation
These operations and functions provide answers to True – False questions. One
important use of this capability is to control the flow or order of execution of a
series of MATLAB commands (usually in an M-file) based on the results of
true/false questions.
Operation Description
== Equal
~= Not equal
< Less than
> Greater than
<= Less than or equal
>= greater than or equal
(5 - 1)
University of Zakho Petroleum Engineering Department MATLAB Laboratory
______________________________________________________________________________________________
Example:
» a = 1:9;
» b = 9-a;
» t = a > 4 %finds elements of (a) that are greater than 4.
t =
0 0 0 0 1 1 1 1 1
Zeros appear where a < 4, and ones where a > 4.
LouicalOperation
Operation Description
& Logical AND
| Logical OR
~ Logical NOT
xor (a,b) Logical Exclusive OR
Example:
» a = [0 4 0 -3 -5 2];
» b = ~a
b =
1 0 1 0 0 0
» c = a & b
0 0 0 0 0 0
Example: Let x= [2 -3 5; 0 1 1 ] , then
a) Find elements in x that are greater than 2.
b) Find the number of nonzero elements in x
Solution
a)
(5 - 2)
University of Zakho Petroleum Engineering Department MATLAB Laboratory
______________________________________________________________________________________________
» x > 2
ans =
0 0 1
0 0 0
b)
» t = ~(~x);
»sum(sum(t))
ans =
5
Exercise:
1- If x= [8 3; 11 5], y = [12 1; 9 13], z = [-2 13; -5 1], what is the output of
the following statements:
a) v = x > y
b) w = z >= y
c) t = x & y < z
(5 - 3)