Create an array with zero above the main diagonal forming a lower triangular matrix in Numpy


To create an array with zero above the main diagonal forming a lower triangular matrix, use the numpy.tri() method in Python Numpy. The 1st parameter is the number of rows in the array. The 2nd parameter is the number of columns in the array.

The tri() function returns an array with its lower triangle filled with ones and zero elsewhere; in other words T[i,j] == 1 for j <= i + k, 0 otherwise.

Steps

At first, import the required library −

import numpy as np

Create an array with zero above the main diagonal forming a lower triangular matrix, use the numpy.tri() −

arr = np.tri(4, 4)

Display the array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array: −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Elements in the Array...
",arr.size)

Example

import numpy as np

# To create an array with zero above the main diagonal forming a lower triangular matrix, use the numpy.tri() method in Python Numpy
# The 1st parameter is the number of rows in the array
# The 2nd parameter is the number of columns in the array
arr = np.tri(4, 4)

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size)

Output

Array...
[[1. 0. 0. 0.]
[1. 1. 0. 0.]
[1. 1. 1. 0.]
[1. 1. 1. 1.]]

Array datatype...
float64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

Updated on: 10-Feb-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements