What is the numpy.tri() Method

Numpy tri() method returns an array with ones at and below the k-th diagonal and zeros elsewhere, where k is the given parameter”.

Syntax

numpy.tri(rows, columns, k, dtype)

Parameters

The tri() function takes four parameters, out of which three parameters are optional. 

  1. rows: It represents the number of rows.
  2. columns: It is the number of columns; by default, it is equal to the number of rows.
  3. k: It is an integer value and 0 by default. If the value of k>0, it means the diagonal is above the main diagonal, and if not, vice versa follows.
  4. dtype: It is optional to mention by default. It takes float. (It is the data type of the returned array).

Return Value

The tri() function returns an array with 1’s and 0’s values.

Example 1: How to Use the numpy.tri() Method

import numpy as np

print("tri with 3 rows 3 col and k=1 : \n", np.tri(3, 3, 1, 
                dtype=float), "\n")
print("tri with 3 rows and 5 columns considering main diagonal : \n",
                np.tri(3, 5, 0), "\n")

print("tri with 3 rows and 5 columns and k=-1: \n", np.tri(3, 5, -1), "\n")

Output

tri with 3 rows 3 col and k=1 : 
 [[1. 1. 0.]
 [1. 1. 1.]
 [1. 1. 1.]] 
 
tri with 3 rows and 5 columns considering main diagonal : 
 [[1. 0. 0. 0. 0.]
 [1. 1. 0. 0. 0.]
 [1. 1. 1. 0. 0.]] 
 
tri with 3 rows and 5 columns and k=-1: 
 [[0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0.]
 [1. 1. 0. 0. 0.]] 

Example 2: Using a 4X4 matrix

import numpy as np

print("tri with 4 rows 4 col and k=1 : \n", np.tri(4, 4, 1, dtype=float), "\n")

Output

tri with 4 rows 4 col and k=1 :
 [[1. 1. 0. 0.]
 [1. 1. 1. 0.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.