How to create an identity matrix in Python
To create an identity array in Python use the identity() method of the numpy module.
import numpy as np
np.identity(n)
The argument n is the size. It is the number of rows and columns of the square matrix.
The method creates the identity array in an array object.
What is an identity matrix? An identity matrix is a square matrix in which the elements of the main diagonal are equal to one and the other elements equal to zero.
Array objects are special lists for vector and matrix computation in the python language.
Example
To create an identity matrix with 4 rows and 4 columns.
import numpy as np
m=np.identity(4)
The method creates an array object, a square matrix of order four, then assigns the object to the variable m.
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
It is an identity matrix
Note. The identity method is included in the NumPy module. Therefore, to use it you must first import the numpy module into the python interpreter.