w3resource

NumPy: Create a 3x3 identity matrix, i.e. diagonal elements are 1,the rest are 0

NumPy: Basic Exercise-27 with Solution

Write a NumPy program to create a 3x3 identity matrix, i.e. the diagonal elements are 1, the rest are 0.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 3x3 identity matrix using np.eye()
x = np.eye(3)

# Printing the created 3x3 identity matrix 'x'
print(x)

Sample Output:

[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]                         

Explanation:

An identity matrix is a square matrix with ones on its main diagonal and zeros elsewhere.

In the above code the line ‘x = np.eye(3)’ uses the np.eye() function to create a 2-dimensional square identity matrix 'x' of size 3x3.

Finally print(x) prints the generated identity matrix to the console.

Pictorial Presentation:

NumPy: Create a 3x3 identity matrix, i.e. diagonal elements are 1,the rest are 0.

Python-Numpy Code Editor:

Previous: NumPy program to find the number of rows and columns of a given matrix.
Next: NumPy program to create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.