w3resource

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


Create 3x3 Identity Matrix

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

This problem involves writing a NumPy program to generate a 3x3 identity matrix, where all diagonal elements are 1 and the rest are 0. The task requires leveraging NumPy's identity function, which efficiently constructs such matrices of any desired size with the specified diagonal values. The resulting identity matrix aids in various mathematical operations, such as linear transformations and solving systems of equations.

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)

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.

Visual Presentation:

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

Python-Numpy Code Editor: