+2 votes
in Programming Languages by (73.8k points)
What Python function should I use to generate an identity matrix of size NxN (a square Matrix with diagonal 1 and other elements 0)

E.g.

[[1., 0., 0., 0., 0.],

[0., 1., 0., 0., 0.],

[0., 0., 1., 0., 0.],

[0., 0., 0., 1., 0.],

[0., 0., 0., 0., 1.]]

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

You can use Numpy's eye() or identity() function to generate an identity matrix. If you want to generate an identity matrix of size NxN, you need to specify N as a parameter of the function.

Here is an example:

>>> import numpy as np
>>> np.identity(5)
array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.]])
>>> np.eye(4)
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])


...