NumPy: Set zero to lower triangles along the last two axes of a three-dimensional of a given array
Set lower triangles of a 3D array to zero.
Write a NumPy program to set zero to lower triangles along the last two axes of a three-dimensional of a given array.
Sample Solution:
Python Code:
# Importing NumPy library
import numpy as np
# Creating a NumPy array of shape (1, 8, 8) filled with ones
arra = np.ones((1, 8, 8))
# Printing the original array
print("Original array:")
print(arra)
# Computing the upper triangular part of the array with diagonal offset 1
result = np.triu(arra, k=1)
# Printing the resulting upper triangular matrix
print("\nResult:")
print(result)
Sample Output:
Original array: [[[1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1.]]] Result: [[[0. 1. 1. 1. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1. 1. 1.] [0. 0. 0. 1. 1. 1. 1. 1.] [0. 0. 0. 0. 1. 1. 1. 1.] [0. 0. 0. 0. 0. 1. 1. 1.] [0. 0. 0. 0. 0. 0. 1. 1.] [0. 0. 0. 0. 0. 0. 0. 1.] [0. 0. 0. 0. 0. 0. 0. 0.]]]
Explanation:
In the above code -
arra=np.ones((1,8,8)): This line creates a 3-dimensional NumPy array of shape (1, 8, 8) filled with ones.
result = np.triu(arra, k=1): This line generates a new NumPy array with the same shape as ‘arra’, retaining the upper triangular elements of ‘arra’ and setting all elements below the diagonal to zero. The parameter k=1 indicates that the elements on the diagonal should also be set to zero, effectively making the result an upper triangular matrix with a zero diagonal.
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics