Determine whether a matrix is identity matrix (numpy)

Viewed 7466

What is the best way to determine whether a given matrix 'M' is equal to identity? I.e. something like:

if numpy.identity(3) == M:
     ...
3 Answers

You can also use the built-in function np.equal() combined with np.all() like:

In [242]: I = np.eye(3)
In [243]: M = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]])

In [244]: np.all(np.equal(M, I))
Out[244]: True
Related