w3resource

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:

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

For more Practice: Solve these Related Problems:

  • Write a NumPy program to zero out the lower triangular part of each 2D slice in a 3D array using np.tril.
  • Create a function that iterates over the first axis of a 3D array and applies np.tril to each slice.
  • Implement a solution that uses broadcasting to subtract a lower-triangular mask from each 2D sub-array.
  • Test the solution on a 3D array with non-square 2D slices and verify that only the lower triangle is zeroed.

Go to:


PREV : Store non-zero unique rows from a matrix.
NEXT : Get array metadata (dimensions, size, etc.).


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.