The numpy.matlib.eye()
function is used to return a matrix with all the diagonal elements initialized to 1 and with zero value elsewhere.
The numpy.matlib
is a matrix library used to configure matrices instead of ndarray objects.
Syntax of matlib.eye()
:
The required syntax to use this function is as follows:
numpy.matlib.eye(n, m, k, dtype,order)
Parameters:
Let us now cover the parameters used with this function:
- n
This parameter is used to represent the number of rows in the resulting matrix. - m
This parameter is used to represent the number of columns and the default value isn
. - k
This parameter is used to indicate an index of diagonal,value of this parameter is 0 by default if value of k>0 it means diagonal is above the main diagonal or vice versa. - dtype
This parameter is used to indicate the data type of the matrix. The default value of this parameter isfloat
. This is an optional parameter. - order
This is an optional parameter that is used to indicate the insertion order of the matrix. It mainly indicates whether to store the result in C- or Fortran-contiguous order, The default value is ‘C’.
Returned Values:
This method will return a n x M matrix where all elements are equal to zero, except for the kth diagonal, whose values are equal to one.
Example 1:
Given below is a basic example for the understanding of this function:
import numpy as np
import numpy.matlib
x = numpy.matlib.eye(n = 4, M = 3, k = 0, dtype = int)
print("The Output is :")
print(x)
The Output is :
[[1 0 0]
[0 1 0]
[0 0 1]
[0 0 0]]
Example 2:
Let’s take another example, to create a matrix of different dimensions.
import numpy as np
import numpy.matlib
x = numpy.matlib.eye(n = 5, M = 4, k = 1, dtype = int)
print("The Output is :")
print(x)
The Output of the above code:
Difference between eye()
and identity()
:
There is a difference between the Numpy identity() function and eye()
function and that is, the 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 with respect to the value of K parameter, if value of K > 0 then it implies the diagonal above main diagonal and vice-versa.