# Create an array with ones below the main diagonal and zeros elsewhere in Numpy

NumpyServer Side ProgrammingProgramming

To create an array with ones below the main diagonal and zeros elsewhere, 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 3rd parameter 'k' is the sub-diagonal at and below which the array is filled.

The k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0. 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

Now, create an array with ones below the main diagonal and zeros elsewhere, using the numpy.tri() method −

arr = np.tri(4, 4, k = -1)


Display the array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)


Get the dimensions of the Array: −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the array −

print("\nOur Array Shape...\n",arr.shape)


Get the number of elements of the Array −

print("\nElements in the Array...\n",arr.size)

## Example

import numpy as np

# To create an array with ones below the main diagonal and zeros elsewhere, 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 3rd parameter 'k' is the sub-diagonal at and below which the array is filled.
# The k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0.
arr = np.tri(4, 4, k = -1)

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nElements in the Array...\n",arr.size)

## Output

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

Array datatype...
float64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16
Updated on 10-Feb-2022 07:31:48