NumPy identity() function
In this tutorial, we will cover
numpy.matlib.identity() function of the Numpy library.
numpy.matlib.identity() function is used to return an identity matrix of the given size. Let us understand the concept of identity matrix first.
An Identity matrix is a matrix with all the diagonal elements initialized to 1 and rest all other elements to zero.
The required syntax to use this function is as follows:
Let us now cover the parameters used with this function:
This parameter is used to indicate the size of the returned identity matrix.
This parameter is used to indicate the data type of the matrix. The default value of this parameter is
This method will return a n x n matrix with its main diagonal elements set to one, and all other elements set to zero.
Below we have a basic example for this method:
import numpy as np import numpy.matlib a = numpy.matlib.identity(4) print("The Identity matrix as output is :") print(a)
The Identity matrix as output is :
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
Given below is a basic example where we will mention the
dtype for the elements of the array
import numpy as np import numpy.matlib a = numpy.matlib.identity(6, dtype = int) print("The Identity matrix as an output is :") print(a)
The Identity matrix as an output is :
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]]
There is a difference between
identity() and the Numpy eye() function and that is identity function returns a square matrix having ones on the main diagonal like this;
eye() function returns a matrix having 1 on the diagonal and 0 elsewhere, which is based on the value of K parameter. If value of K > 0 then it implies the diagonal above main diagonal and vice-versa
In this tutorial we learned about
numpy.matlib.identity() mathematical function of the Numpy library. We covered its syntax, parameters as well as the value returned by this function along with a few code examples.