Python’s triu()
function is used for the upper triangle of a given array.
triu(m, k=0)
The triu()
function takes the following parameter values:
m
: This represents the array_like object or the input array.k
: This represents the diagonal above or below the main diagonal. K<0
is below the main diagonal, and k>0
is above the main diagonal. This is optional.The triu()
function returns an upper triangle of the same shape and data type as the array m
passed to it.
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the triu() functiontriuarray = np.triu(myarray, k=0)print(myarray)print(triuarray)
numpy
library.myarray
containing 9
arrange with a dimension of 3 by 3
(i.e 3
rows and 3
columns) using the arange()
function.triu()
function on the array myarray
using the main diagonal k = 0
. The result is assigned to a new variable triuarray
.myarray
.triuarray
.It is worth noting that in the code example above we returned an upper triangle of an array that starts from the main or default diagonal. For the main diagonal,
k = 0
.
Now let us return an upper triangle of an array below (k < 0
) the main or default diagonal.
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the triu() functiontriuarray = np.triu(myarray, k=-1)print(myarray)print(triuarray)
Similar to the first example but here we use a diagonal value which is below (k < 0
) the main diagonal. This simply means that our upper triangle array will start before the main diagonal as can be seen in the code’s output.
Now let us return an upper triangle of an array above (k > 0
) the main or default diagonal.
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the triu() functiontriuarray = np.triu(myarray, k = 1)print(myarray)print(triuarray)
Similar to the first example but here we use a diagonal value which is above (k > 0
) the main diagonal. This simply means that the upper triangle array will start after the main diagonal as can be seen in the code’s output.