w3resource

NumPy: Get a copy of a matrix with the elements below the k-th diagonal zeroed

NumPy: Array Object Exercise-154 with Solution

Write a NumPy program to get a copy of a matrix with the elements below the k-th diagonal zeroed.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a matrix with specified elements
# The parameter -1 will set the main diagonal and elements below it to zero
result = np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)

# Displaying a message indicating the copied matrix with elements below the k-th diagonal zeroed
print("\nCopy of a matrix with the elements below the k-th diagonal zeroed:")

# Printing the resulting matrix after applying the triu function
print(result) 

Sample Output:

Copy of a matrix with the elements below the k-th diagonal zeroed:
[[ 1  2  3]
 [ 4  5  6]
 [ 0  8  9]
 [ 0  0 12]]

Explanation:

In the above code –

result = np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1): The np.triu() function takes a 2D array as input and returns the upper triangle of the array by setting all elements below the specified diagonal to zero. In this case, the input is a 4x3 array, and the second argument -1 specifies the diagonal below the main diagonal. So, the function will return the upper triangle of the input array including the elements on the diagonal below the main diagonal.

Finally print() function prints the resulting 2D array, which is the upper triangle of the input array with elements below the specified diagonal set to zero.

Python-Numpy Code Editor:

Previous: Write a NumPy program to extract upper triangular part of a numpy matrix.
Next: Write a NumPy program to check whether a Numpy array contains a specified row.

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.