Let us explore how this function works and how to use it.
What is an identity array?
Before proceeding further, it is good to clarify what an identity array is.
An identity array refers to a square array with the ones in the main diagonal. In simple terms, an identity array is an array that holds ones in the main diagonal while the rest of the elements are populated with zeros.
The above is an example of an identity array.
NumPy identity() Function Syntax
The function has a simple syntax as shown below:
numpy.identity(n, dtype=None, *, like=None)
- n – refers to the dimensions of the output array. The order is rows and columns.
- dtype – specifies the data type of the output array.
Function Return Value
The function returns an identity array of the specified shape, i.e., n x n.
Take the example shown below:
# import numpy
import numpy as np
# generate square array
The code above should generate an identity array with five rows and five columns. The resulting output is as shown:
[[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.]]
You can also specify the data type of the array elements to be floating-point values. An example code is shown below:
The resulting array is as shown:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Through this article, you learned what an identity array is. You also learned how to generate an identity array of the shape n x n using the NumPy identity function.
Stay tuned for more!!