Set Diagonal of 3×3 Matrix as inf in Python
In this tutorial, you will learn how to set the diagonal of a 3×3 matrix as inf in Python using the Numpy library.
First, we need to install Numpy by using the command:
pip install numpy
and then import the Numpy library:
import numpy as np
Now create a 3×3 matrix, you can make a matrix with zeros:
matrix = np.zeros((3,3))
Set the diagonal elements to infinity (inf) by using Numpy, np.fill_diagonal function and pass np. inf as value :
np.fill_diagonal(matrix, np.inf)
Finally, print the matrix to get the result:
print(matrix)
The complete code is given below:
import numpy as np #create a 3x3 matrix matrix = np.zeros((3,3)) #set the diagonal elements as inf by using Numpy np.fill_diagonal(matrix, np.inf) #print the matrix print(matrix)
When you run this code you get the output:
[[inf 0 0] [0 inf 0 ] [0 0 inf ]]
Leave a Reply