+2 votes
in Programming Languages by (17.9k 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

0 votes
by (31.6k points)

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.]])

...