How to create an identity matrix with numpy

How to create an identity matrix with numpy? Is there a simpler syntax than

numpy.matrix(numpy.identity(n)) 
+6
source share
3 answers

Here is a simpler syntax:

 np.matlib.identity(n) 

And here is 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 
+13
source

I do not think there is a simpler solution. You can do this somewhat more efficiently though:

 numpy.matrix(numpy.identity(n), copy=False) 

This avoids unnecessary data copying.

+5
source

In addition, np.eye can be used to create an array of identifiers (In).

For instance,

 >>> 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.]]) 
+4
source

Source: https://habr.com/ru/post/917541/


All Articles