Relational operators compare operands quantitatively, using operators like "less than", "greater than", and "not equal to." The result of a relational comparison is a logical array indicating the locations where the relation is true.

These are the relational operators in MATLAB^{®}.

Symbol | Function Equivalent | Description |
---|---|---|

`<` | `lt` | Less than |

`<=` | `le` | Less than or equal to |

`>` | `gt` | Greater than |

`>=` | `ge` | Greater than or equal to |

`==` | `eq` | Equal to |

`~=` | `ne` | Not equal to |

The relational operators perform element-wise comparisons between two arrays. The arrays must be the same size, or one can be a scalar.

For example, if you compare two matrices of the same size, then the result is a logical matrix of the same size with elements indicating where the relation is true.

A = [2 4 6; 8 10 12]

A = 2 4 6 8 10 12

B = [5 5 5; 9 9 9]

B = 5 5 5 9 9 9

A < B

ans = 1 1 0 1 0 0

Similarly, you can compare one of the arrays to a scalar.

A > 7

ans = 0 0 0 1 1 1

The relational operators work with arrays for which any dimension has size zero. If one array has a dimension size of zero, then the other array must either be the same size or be a scalar. The size of that dimension in the output is also zero.

A = ones(3,0); A == 1

ans = Empty matrix: 3-by-0

However, expressions such as

A == []

return an error if `A`

is not 0-by-0 or 1-by-1.
This behavior is consistent with that of all other binary operators,
such as `+`

, `-`

, `>`

, `<`

, `&`

, `|`

,
and so on.

To test for empty arrays, use `isempty(A)`

.

The operators

`>`

,`<`

,`>=`

, and`<=`

use only the real part of the operands in performing comparisons.The operators

`==`

and`~=`

test both real and imaginary parts of the operands.

`Inf`

, `NaN`

, `NaT`

, and undefined Element Comparisons`Inf`

values are equal to other`Inf`

values.`NaN`

values are not equal to any other numeric value, including other`NaN`

values.`NaT`

values are not equal to any other datetime value, including other`NaT`

values.Undefined categorical elements are not equal to any other categorical value, including other undefined elements.

Use relational operators in conjunction with the logical operators ```
A
& B
```

(AND), `A | B`

(OR), `xor(A,B)`

(XOR),
and `~A`

(NOT), to string together more complex logical
statements.

For example, you can locate where negative elements occur in two arrays.

A = [2 -1; -3 10]

A = 2 -1 -3 10

B = [0 -2; -3 -1]

B = 0 -2 -3 -1

A<0 & B<0

ans = 0 1 1 0

For more examples, see Find Array Elements That Meet a Condition.

Was this topic helpful?