numpy.triu() in Python

numpy.triu() returns a copy of the array matrix with an element of the upper part of the triangle with respect to k. It returns a copy of array with upper part of triangle and below the kth diagonal zeroed.

Syntax:

numpy.triu(m,k=0)

Parameters:

m- number of rows in the array.

k-It is optional. Diagonal above which to zero elements. k=0 is the main diagonal and its default.

k>0 is above it and k<0 is below it.

Return value:

It returns a copy of the matrix with elements below the kth diagonal zeroed.

Example:

import numpy as np

m = np.array([[1,2,3],[4,5,6],[7,8,9]])

print(“Sample array”)

print(m)

print(“\ntriu() function without any parameter:”)

print(np.triu(m))

print(“\nBelow 1st diagonal zeroed.”)

print(np.triu(m,-1))

print(“\nBelow 2nd diagonal zeroed.”)

print(np.triu(m,-2))