Here's a simpler syntax:
np.matlib.identity(n)
And here's an even simpler syntax that runs much faster:
In [1]: n = 1000
In [2]: timeit np.matlib.identity(n)
100 loops, best of 3: 8.78 ms per loop
In [3]: timeit np.matlib.eye(n)
1000 loops, best of 3: 695 us per loop
Answer from kwgoodman on Stack OverflowHere's a simpler syntax:
np.matlib.identity(n)
And here's an even simpler syntax that runs much faster:
In [1]: n = 1000
In [2]: timeit np.matlib.identity(n)
100 loops, best of 3: 8.78 ms per loop
In [3]: timeit np.matlib.eye(n)
1000 loops, best of 3: 695 us per loop
Also np.eye can be used to create an identity array (In).
For example,
>>> np.eye(2, dtype=int)
array([[1, 0],
[0, 1]])
>>> np.eye(3, k=1)
array([[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 0., 0.]])
np.eye or np.identity will both return an identity matrix I of specified size. For example:
np.eye(3) # np.identity(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Assuming M is square and with dtype=int, this is how you'd want to test:
assert (M.shape[0] == M.shape[1]) and (M == np.eye(M.shape[0])).all()
Add the check to ensure M is square first. This returns True if the two 2D-arrays are identical.
Alternatively, if M is a float matrix, use np.allclose instead:
assert (M.shape[0] == M.shape[1]) and np.allclose(M, np.eye(M.shape[0]))
A problem with the == is it compares each element, and returns a boolean matrix. That can't be used in the if context (you'll get the common ValueError ... ambiguous error):
In [238]: M=np.diag(1+np.random.random(3)*1e-10)
In [239]: M
Out[239]:
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
In [240]: M==np.eye(3)
Out[240]:
array([[False, True, True],
[ True, False, True],
[ True, True, False]], dtype=bool)
In [241]: np.allclose(M,np.eye(3))
Out[241]: True
np.allclose is a widely used way of comparing arrays. It handles floats more gracefully than ==.
Using all to reduce the array to a scalar is also widely used:
In [242]: (M==np.eye(3)).all()
Out[242]: False
Here I get different results because I deliberately created a float that is close, but not exactly an identity. That's like to be the case when testing for matrix inversion case.