1
©2009 by L. Lagerstrom
Relational Operators
• Relational operations and assignment statements
• Relational operators with arrays
• Innovative uses of relational operators:
Fixing sin(x)/x
Creating a discontinuous sine signal
©2009 by L. Lagerstrom
Relational Operations
Relational operators are the familiar math operators >, <, etc. for
representing inequalities and similar relationships. In Matlab,
however, we use them a little bit differently than we do in regular
math.
In regular math usage, when we write A < B, we mean that A is less
than B. In Matlab, however, when we write A < B, it means for
Matlab to test whether the value of A is less than the value of B and
return the result: true or false. That is, it means “is A less than B?”
So if A has the value 10 and B has the value 7, the result of A < B is
false. If the values were reversed, then obviously the result is true.
Some programming languages use the actual words “true” and
“false” to represent results like these. Matlab, however, like many
other languages, uses the values 0 and 1, where 0 represents false
and 1 represents true.
©2009 by L. Lagerstrom
Relational Assignment Statements
Because Matlab interprets the expression A < B (and similar
expressions) to mean “test if A is less than B and return the
true/false result as either a 1 or a 0,” we can write assignment
statements with relational operators as below. Note that at first
glance they look very weird, but if we remember that for an
assignment statement we first evaluate the expression on the right
side of the assignment operator (the = sign) and then assign
(transfer) the result to the variable on the left side, they make sense
in the context of Matlab.
>>A = 10; B = 7;
>>x = A < B;
%The value of x will be 0 (representing false, i.e.,
%the value of A is not less than the value of B).
>>y = A > B;
%The value of x will be 1 (representing true, i.e.,
%the value of A is less than the value of B).
©2009 by L. Lagerstrom
Matlab’s Relational Operators
The relational operators available in Matlab are listed below. Note
that for “less than or equal to” and “greater than or equal to” we type
two symbols, i.e., <= or >=, in that order (the same order as we
usually say it). But Matlab treats them as a single symbol.
<
is used for “less than”
>
is used for “greater than”
<=
is used for “less than or equal to”
>=
is used for “greater than or equal to”
==
is used for “equal to”
~= is used for “not equal to”
See the next slide for a few comments about the last two operators,
the equality operator and the inequality operator.