6.1: Relational Operators
- Page ID
- 84539
Suppose we have three variables, a
, b
, and c
, and we want to check whether they form a Pythagorean triple. We can use the equality operator (==
) to compare two values:
>> a = 3;
>> b = 4;
>> c = 5;
>> a^2 + b^2 == c^2
ans = logical 1
The result is a logical value, which means it’s either 1
, which means “true,” or 0
, which means “false.” Here’s an example where the result is false:
>> c = 6;
>> a^2 + b^2 == c^2
ans = logical 0
It’s a common error to use the assignment operator (=
) instead of the equality operator (==
). If you do, you get an error:
>> a^2 + b^2 = c^2
a^2 + b^2 = c^2
|
Error: Incorrect use of '=' operator.
To assign a value to a variable, use '='.
To compare values for equality, use '=='.
The equality operator is one of several relational operators, so called because they test relations between values. For example, x < 10
is true (1
) if the value of x
is less than 10
or false (0
) if otherwise. And x > 0
is true if x
is greater than 0
.
The other relational operators are <=
for “less or equal,” >=
for “greater or equal,” and ~=
for “not equal.”