Lecture 8
Lecture 8
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
>> 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];
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