MATLAB - Relational Operations

Advertisements


Relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform element-by-element comparisons between two arrays and 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.

The following table shows the relational operators:

OperatorDescription
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to

Example

Create a script file and type the following code:

a = 100;
b = 200;
if (a >= b)
max = a
else
max = b
end

When you run the file, it produces following result:

max =
   200

Apart from the above-mentioned relational operators, MATLAB provides the following commands/functions used for the same purpose:

FunctionDescription
eq(a, b)Tests whether a is equal to b
ge(a, b)Tests whether a is greater than or equal to b
gt(a, b)Tests whether a is greater than b
le(a, b)Tests whether a is less than or equal to b
lt(a, b)Tests whether a is less than b
ne(a, b)Tests whether a is not equal to b
isequalTests arrays for equality
isequalnTests arrays for equality, treating NaN values as equal

Example

Create a script file and type the following code:

% comparing two values
a = 100;
b = 200;
if (ge(a,b))
max = a
else
max = b
end
% comparing two different values
a = 340;
b = 520;
if (le(a, b))
disp(' a is either less than or equal to b')
else
disp(' a is greater than b')
end

When you run the file, it produces the following result:

max =
   200
 a is either less than or equal to b


Advertisements
Advertisements