What is the identity() function from numpy in Python?

Overview

The identity() function from numpy library is used to return the identity matrix.

Note: An identity matrix is the type of matrix in which all the elements on the main diagonal are ones (1) and all other elements are zeros (0).

Syntax

identity(n, dtype=float, like=None)

Parameter value

The identity() function takes the following parameter values:

  • n: This represents the number of rows in the output.
  • dtype: This represents the data type of the output matrix. This is optional and its default type is float.
  • like: This represents the matrix-like object or the prototype.

Return value

The identity() function returns a square identity of nn by nn with its main or principal diagonal set to 1 and all other elements to 0.

Example

from numpy import identity
# creating an identity matrix with four rows
identity_matrix = identity(4)
print(identity_matrix)

Explanation

  • Line 1: We import identity() from the numpy module.
  • Line 4: Using the identity() function, we create an identity matrix with 4 rows. The output is stored in the variable identity_matrix.
  • Line 6: We print the variable identity_matrix.

Free Resources