Equality of two matrices

When working with matrices in NumPy, it is often necessary to compare them for equality. This can be useful in a variety of scenarios, such as checking if two matrices have the same dimensions and values or verifying if a calculation has produced the expected result. In this thread, we will discuss some techniques that help to determine the equality of two matrices.

1. Using "array_equal()" function:

The array_equal() function in NumPy is used to compare two arrays for equality element-wise. The function returns True if the two arrays have the same shape and the same elements in each position, and False otherwise. It is useful when we need to compare two arrays of numerical data or when we need to test if two arrays are equal for testing purposes.

The array_equal() method is used to check if both matrices are equal or not. Let’s see the example given below to gain better understanding:

In the above example, two arrays, matrix_A and matrix_B , are generated using NumPy’s random.rand() function. The array_equal() function is then used to compare the two arrays for equality. If the arrays are equal, the code prints the message “Arrays A and B are equal”. Otherwise, it prints the message “Arrays A and B are not equal”.

2. Using "allclose()" function:

The allclose() function in NumPy is used to check whether all corresponding pairs of elements in two arrays are equal or not. The function returns True if the elements are equal up to a certain tolerance value, and False otherwise. This is useful when comparing two arrays that may have small differences due to floating point errors

The allclose() method is used to check if both matrices are equal or not. Let’s see the example given below to gain better understanding:

The code generates two arrays of random integers between 0 and 10 using NumPy’s randint function, and then uses the allclose function to check if the arrays are approximately equal. If the arrays are approximately equal, the code will print “A and B are equal.”, and if not, it will print “A and B are not equal.”.