Check if two given matrices are identical Python (original) (raw)

Last Updated : 15 Jan, 2025

In Python, we often need to check whether two given matrices are identical. Two matrices are considered identical if they have the same number of rows and columns and the corresponding elements in each matrix are equal. Let’s explore various methods to compare two matrices and check if they are identical.

**Using equality operator (==)

equality operator can be used to directly compare two matrices. Python lists support element-wise comparison, so this method is simple and efficient.

Python `

Input matrices

m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[1, 2, 3], [4, 5, 6]]

Check if matrices are identical

res = m1 == m2 print(res)

`

Explanation:

Let’s explore some more methods and see how we can check if two given matrices are identical.

Table of Content

**Using zip()

zip() function can be used to pair up the rows of both matrices and then compare each pair.

Python `

m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[1, 2, 3], [4, 5, 6]]

Check if matrices are identical using zip

res = all(r1 == r2 for r1, r2 in zip(m1, m2)) print(res)

`

Explanation:

**Using for loop

We can also compare two matrices manually using nested loops. This method iterates over each element and checks if they are equal.

Python `

m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[1, 2, 3], [4, 5, 6]]

Initialize result as True

res = True

Check if matrices have the same dimensions and elements

for i in range(len(m1)): for j in range(len(m1[i])): if m1[i][j] != m2[i][j]: res = False break if not res: break print(res)

`

Explanation:

**Using numpy for large matrices

When working with large matrices, the numpy library offers a very efficient way to compare matrices using the numpy.array_equal() function.

Python `

import numpy as np

Input matrices

m1 = np.array([[1, 2, 3], [4, 5, 6]]) m2 = np.array([[1, 2, 3], [4, 5, 6]])

Check if matrices are identical

res = np.array_equal(m1, m2) print(res)

`

Explanation:

Similar Reads