Signup/Sign In
LAST UPDATED: DECEMBER 17, 2020

NumPy identity() function

In this tutorial, we will cover numpy.matlib.identity() function of the Numpy library.

The 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.

Syntax of matlib.identity():

The required syntax to use this function is as follows:

numpy.matlib.identity(n, dtype)

Parameters:

Let us now cover the parameters used with this function:

  • n
    This parameter is used to indicate the size of the returned identity matrix.

  • dtype
    This parameter is used to indicate the data type of the matrix. The default value of this parameter is float.

Returned Values:

This method will return a n x n matrix with its main diagonal elements set to one, and all other elements set to zero.

Example 1:

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.]]

Example 2:

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]]

Difference between identity() and eye():

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;

while the 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

Summary

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.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.