SCIENTIFIC COMPUTING
LECTURE # 8
RELATIONAL OPERATORS &
LOGICAL OPERATORS
Relational operators
A relational operator performs a comparison and returns true or false
(Boolean values)
Examples
1 > 2 → False
(12/4) == 1.5*2 → True
In MATLAB
true is represented as 1
false is represented as 0
Relational Operators in MATLAB
> greater than
>= greater than or equal to
< less than
<= less than or equal to
== equal to
~= not equal to
Example
>> x = 2;
>> y = 10;
>> y/x >= 5
ans =
1
>> y/5 ~= x
ans =
0
Relational operations can be performed on matrices
(element by element)
>> x = [5 6 7; 8 9 10];
>> y = [2 4 6; 8 10 12];
>> z = x >= y
z =
1 1 1
1 0 0
Logical operators
Logical operators work with Boolean values
Logical operators in MATLAB:
& and combines 2 result is true if both
conditions conditions are true
| or combines 2 result is true if either
conditions condition is true
~ not negates a result is true if condition
condition is false
and (&) example
>> x = 2; 0 1
>> y = 10;
>> rem(x,5) == 0 & rem(y,5) == 0
ans =
Requires both conditions
to be 1 (true) to give 1
0 (true)
as an answer
and (&) example
>> x = 2;
>> y = 10;
>> rem(x,5) == 0 & rem(y,5) == 0
ans =
0
or (|) example
>> x = 2; 0 1
>> y = 10;
>> rem(x,5) == 0 | rem(y,5) == 0
ans =
Requires at least one
condition to be true to
1 give an true as an
answer
Exercise 1:
• Write MATLAB code to compare elements of two matrices A and B,
and return a matrix of logical values (true/false) indicating whether
each element in A is greater than or equal to the corresponding
element in B.
10
Exercise 1:
• Write MATLAB code to compare elements of two matrices A and B,
and return a matrix of logical values (true/false) indicating whether
each element in A is greater than or equal to the corresponding
element in B.
• Answer:
11
Exercise 2:
• Given the following matrices:
A = [4 7 2; 5 9 1]; B = [3 7 3; 6 8 0];
Write MATLAB code to:
1. Find the positions where both elements in A and B are greater than or
equal to 5.
2. Find the positions where either element in A or B is equal to 7.
12
Exercise 2: Answer
13
Exercise 3:
• Given two variables x = 15 and y = 9, write MATLAB code to:
1. Check if both x and y are divisible by 3.
2. Check if at least one of them is divisible by 5.
14
Exercise 3: Answer
15
16
Any Questions