# 1. Objectives

• To introduce the use of relational operators.

# 2. Motivation

• Conditions in if statements can be formed by using relational operators, which are commonly used in computational decision making.

# 3. Pre-questions

• As a mathematical inequality, 0 < 0.5 < 1 is undoubtedly true from a nonoperational point of view. However, as a MATLAB expression, this is false. Does this make sense to you, and why?

# 4. Slides

== Relational Operators

• Matlab, similar to other programming languages, uses six relational operators to make comparisons between values and arrays.
• The relational operators are <, >, <=, >=, ==, and ~=.

Syntax:
A < B
A > B
A <= B
A >= B
A == B
A ~= B

• The relational operators all have the same level of precedence and associate left to right.
• Relational operators perform element-by-element comparisons between two arrays. They return a logical array of the same size, with elements set to logical 1 (true) where the relation is true, and elements set to logical 0 (false) where it is not.

## 4.1. Example I

The following statements all assign relational expressions to the variable x. See if you can correctly determine the value of x in each case before checking your results with MATLAB.

(a) x = 3 > 2
(b) x = 2 > 3
(c) x = -4 <= -3
(d) x = 1 < 1
(e) x = 2 ~=2
(f) x = 3 == 3
(g) x = 0 < 0.5 < 1


## 4.2. Example II

 x = [6, 3, 9];
y = [14, 2, 9 ];
z = (x < y)

z =
1  0 0


## 4.3. Common Errors

• A syntax error will occur if any of the operators ==, ~=, >= and <= appears with spaces between its pair of symbols.
• Reversing the order of the pair of symbols in any of the operators ~=, >= and <= (by writing them as =~, => and =<, respectively) is normally a syntax error.
• Confusing the equality operator == with the assignment operator = results in logic errors.

## 4.4. Example II

If one of the operands is a scalar and the other a matrix, the scalar expands to the size of the matrix. For example, the two pairs of statements

X = 5; X >= [1 2 3; 4 5 6; 7 8 10]

X = 5*ones(3,3); X >= [1 2 3; 4 5 6; 7 8 10]

produce the same result. What is the result?