w3resource

NumPy: Set zero to lower triangles along the last two axes of a three-dimensional of a given array

NumPy: Array Object Exercise-173 with Solution

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:

NumPy: Set zero to lower triangles along the last two axes of a three-dimensional of a given array

Python-Numpy Code Editor:

Previous: Write a NumPy program to find and store non-zero unique rows in an array after comparing each row with other row in a given matrix.
Next: Write a NumPy program to get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array.

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.