How to Compare Two Matrices in MATLAB?
The relational operators compare each element of two matrices at a time. To make this procedure easier, both matrices must have equal dimensions. In the most basic situation, either both operands are scalars or both operands are identical-sized matrices to perform a comparison between them. The relational operators used for performing matrices comparison are listed below:
- Greater than > operator
- Less than < Operator
- Equal to == operator
- Not equal to ~= operator
Let’s explain how to compare two matrices using these operators.
How to Compare Two Matrices Using > Operator?
The greater than or > operator in MATLAB is used for comparing all elements of the given two matrices. For example, if we want to compare two matrices A and B by specifying the condition A>B, then a third matrix having equal size to A and B will be returned containing logical values 0 and 1. The logical value 1 will be returned if the specified condition is true otherwise, it will return false.
B = zeros (3);
A > B
How to Compare Two Matrices Using < Operator?
The less than or < operator is used for comparing all entries of the given two matrices in MATLAB. For example, if we want to compare two matrices A and B by specifying the condition A<B, then a third matrix having equal size to A and B will be returned containing logical values 0 and 1. The logical value 1 will be returned if the specified condition is true otherwise, it will return false.
B = zeros (3);
A < B
How to Compare Two Matrices Using == Operator?
The equal to or == operator allows us to compare all components of the given two matrices in MATLAB. For example, if we want to compare two matrices A and B by specifying the condition A==B, then a third matrix having equal size to A and B will be returned containing logical values 0 and 1. The logical value 1 will be returned if the specified condition is true otherwise, it will return false.
B = zeros (3);
A == B
How to Compare Two Matrices Using ~= Operator?
The not equal to or ~= operator compares all members of the given two matrices in MATLAB. For example, if we want to compare two matrices A and B by specifying the condition A~=B, then a third matrix having equal size to A and B will be returned containing logical values 0 and 1. The logical value 1 will be returned if the specified condition is true otherwise, it will return false.
B = zeros (3);
A ~= B
Conclusion
MATLAB supports matrix comparison using relation operators including greater than, smaller than, equal to, and, not equal to. These relational operators compare each element of two matrices at a time. To make this procedure easier, both matrices must have equal dimensions. This tutorial explored how to compare two matrices in MATLAB.