Python NumPy - Set Diagonal of a 3x3 Matrix as inf

By IncludeHelp Last updated : March 8, 2024

In NumPy, inf is a floating-point value that represents positive infinity. Whenever a calculation exceeds the possible limit of representation, we use inf to represent it.

Problem Statement

Given the NumPy matrix of shape 3X3, we need to set the diagonals of this matrix as inf values.

Setting Diagonal of a 3x3 Matrix as inf

To set the diagonal of a 3X3 matrix as inf, we first need to create a 3X3 matrix of zeros by using np.zeros() which will fill all the elements as 0 and then we can use np.fill_diagonals() function and pass np.inf() as parameter.

Let us understand with the help of an example,

Python Code to Set Diagonal of a 3x3 Matrix as inf

# Importing numpy
import numpy as np

# Creating an array
arr = np.zeros((3, 3))

# Display original array
print("Original array:\n", arr, "\n")

# Assigning diagonal as inf
np.fill_diagonal(arr, np.inf)

# Display result
print("Result:\n", arr)

Output

The output of the above program is:

Original array:
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]] 

Result:
 [[inf  0.  0.]
 [ 0. inf  0.]
 [ 0.  0. inf]]

To understand the above program, you should have the basic knowledge of the following Python topics:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.