How to create an identity matrix using Numpy?

PythonNumpyServer Side ProgrammingProgramming

In this program, we will print an identity matrix of size nxn where n will be taken as an input from the user. We shall use the identity() function in the numpy library which takes in the dimension and the data type of the elements as parameters

Algorithm

Step 1: Import numpy.
Step 2: Take dimensions as input from the user.
Step 3: Print the identity matrix using numpy.identity() function.

Example Code

import numpy as np

dimension = int(input("Enter the dimension of identitiy matrix: "))
identity_matrix = np.identity(dimension, dtype="int")
print(identity_matrix)

Output

Enter the dimension of identitiy matrix: 5
[[1 0 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]
raja
Updated on 16-Mar-2021 10:20:45

Advertisements