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

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.
an example of an identity matrix

Array objects are special lists for vector and matrix computation in the python language.


To create an identity matrix with 4 rows and 4 columns.

import numpy as np

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

the identity matrix of order 4 equivalent to the array

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.


Report us an error or send a suggestion to improve this page

Matrix in Python