Introduction
In this lab, we will learn about the NumPy eye() function, which creates a matrix with diagonal elements as 1 and all other elements as 0. We will cover the syntax, parameters along with some examples to understand this function.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Import the NumPy library
Before using NumPy library and its functions we need to import it. We will import it using the following code:
import numpy as np
Create a matrix using eye() function
We will create a matrix using eye() function. This function returns a matrix with diagonal elements as 1 and all other elements as 0.
x = np.eye(4,4)
print(x)
Output:
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
Create a matrix with diagonal elements off the main diagonal
We can create a matrix with diagonal elements off the main diagonal by using the k parameter. If k=1 then diagonal will be shifted to one position to the right and if k=-1 then diagonal will be shifted to one position to the left. k=0 represents main diagonal.
y = np.eye(4,4,k=1)
print(y)
Output:
array([[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.],
[0., 0., 0., 0.]])
Create a matrix of integer datatype
We can create a matrix of integer datatype by specifying dtype parameter as int.
z = np.eye(4,4,dtype=int)
print(z)
Output:
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
Create a matrix with different number of rows and columns
We can create a matrix of any number of rows and columns by specifying the number of rows and columns in the eye() function.
w = np.eye(3,4,k=-1,dtype=int)
print(w)
Output:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]])
Difference between eye() and identity() functions
The identity() function creates a square matrix with diagonal elements as 1 and all other elements as 0. Whereas the eye() function creates a matrix of any number of rows and columns with diagonal elements as 1 and all other elements as 0.
i = np.identity(4,dtype=int)
print(i)
output:
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]
Summary
In this lab, we learned about the NumPy eye() function which creates a matrix with diagonal elements as 1 and all other elements as 0. We covered the syntax, parameters along with some examples to understand this function.