0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use Comparison Operators in MATLAB: Syntax and Examples

In MATLAB, use ==, ~=, <, >, <=, and >= to compare values. These operators return logical true (1) or false (0) based on the comparison result.
๐Ÿ“

Syntax

Comparison operators in MATLAB compare two values or arrays element-wise and return logical results.

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

They work with numbers, characters, and arrays of the same size.

matlab
A == B
A ~= B
A < B
A > B
A <= B
A >= B
๐Ÿ’ป

Example

This example compares two arrays element-wise using different comparison operators and shows the logical output.

matlab
A = [1, 3, 5, 7];
B = [2, 3, 4, 8];

isEqual = A == B
isNotEqual = A ~= B
isLess = A < B
isGreaterEqual = A >= B
Output
isEqual = 0 1 0 0 isNotEqual = 1 0 1 1 isLess = 1 0 0 1 isGreaterEqual = 0 1 1 0
โš ๏ธ

Common Pitfalls

One common mistake is using a single = (assignment) instead of == (comparison), which causes errors or unexpected results.

Also, when comparing arrays, ensure they have the same size; otherwise, MATLAB will throw an error.

matlab
x = 5;

% Wrong: assignment instead of comparison
% if x = 5
%     disp('Equal')
% end

% Right: use double equals for comparison
if x == 5
    disp('Equal')
end
Output
Equal
๐Ÿ“Š

Quick Reference

OperatorMeaning
==Equal to
~=Not equal to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to
โœ…

Key Takeaways

Use double equals (==) for equality comparison, not single equals (=).
Comparison operators return logical arrays of 1 (true) or 0 (false).
Operators work element-wise on arrays of the same size.
Common operators include ==, ~=, <, >, <=, and >=.
Always check array sizes before comparing to avoid errors.