# triu¶

paddle.fluid.layers.triu(input, diagonal=0, name=None)[source]

This op returns the upper triangular part of a matrix (2-D tensor) or batch of matrices input, the other elements of the result tensor are set to 0. The upper triangular part of the matrix is defined as the elements on and above the diagonal.

Parameters
• input (Variable) – The input variable which is a Tensor. Support data types: float64, float32, int32, int64.

• diagonal (int, optional) – The diagonal to consider, default value is 0. If diagonal = 0, all elements on and above the main diagonal are retained. A positive value excludes just as many diagonals above the main diagonal, and similarly a negative value includes just as many diagonals below the main diagonal. The main diagonal are the set of indices $$\{(i, i)\}$$ for $$i \in [0, \min\{d_{1}, d_{2}\} - 1]$$ where $$d_{1}, d_{2}$$ are the dimensions of the matrix.

• name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to Name.

Returns

Tensor, results of upper triangular operation by the specified diagonal of input tensor, it’s data type is the same as input’s Tensor.

Return type

Variable

Raises
• TypeError – diagonal is not a int type.

• ValueError – dimension of input is less than 2.

Examples

import numpy as np
import paddle.fluid as fluid

data = np.arange(1, 13, dtype="int64").reshape(3,-1)
# array([[ 1,  2,  3,  4],
#        [ 5,  6,  7,  8],
#        [ 9, 10, 11, 12]])
x = fluid.data(shape=(-1, 4), dtype='int64', name='x')
exe = fluid.Executor(fluid.CPUPlace())

# example 1, default diagonal
import paddle.fluid as fluid
triu = fluid.layers.triu(x)
triu_out, = exe.run(fluid.default_main_program(), feed={"x": data},
fetch_list=[triu], return_numpy=True)
# array([[ 1,  2,  3,  4],
#        [ 0,  6,  7,  8],
#        [ 0,  0, 11, 12]])

# example 2, positive diagonal value
import paddle.fluid as fluid
import numpy as np

data = np.arange(1, 13, dtype="int64").reshape(3,-1)
x = fluid.data(shape=(-1, 4), dtype='int64', name='x')
exe = fluid.Executor(fluid.CPUPlace())

triu = fluid.layers.triu(x, diagonal=2)
triu_out, = exe.run(fluid.default_main_program(), feed={"x": data},
fetch_list=[triu], return_numpy=True)
# array([[0, 0, 3, 4],
#        [0, 0, 0, 8],
#        [0, 0, 0, 0]])

# example 3, negative diagonal value
import paddle.fluid as fluid
import numpy as np

data = np.arange(1, 13, dtype="int64").reshape(3,-1)
x = fluid.data(shape=(-1, 4), dtype='int64', name='x')
exe = fluid.Executor(fluid.CPUPlace())

triu = fluid.layers.triu(x, diagonal=-1)
triu_out, = exe.run(fluid.default_main_program(), feed={"x": data},
fetch_list=[triu], return_numpy=True)
# array([[ 1,  2,  3,  4],
#        [ 5,  6,  7,  8],
#        [ 0, 10, 11, 12]])