Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create identity matrix with numpy

Tags:

python

numpy

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

numpy.matrix(numpy.identity(n))
like image 596
Johan Råde Avatar asked Jun 07 '12 16:06

Johan Råde


2 Answers

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
like image 51
kwgoodman Avatar answered Oct 01 '22 19:10

kwgoodman


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.]])
like image 40
Anoop Toffy Avatar answered Oct 01 '22 18:10

Anoop Toffy