PyTorch torch.triu function
PyTorch torch reference manual
torch.triu is a function in PyTorch used to extract the upper triangular part of a matrix (including the main diagonal). The lower triangular part is set to 0.
Function definition
torch.triu(input, diagonal=0, out=None)
Parameter Description:
input: the input tensordiagonal: Diagonal index; 0 means the main diagonalout: Output tensor
Usage examples
Example
import
torch
Create a matrix
a
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
Extract the upper triangular part
y
=
torch.
triu
(
a
)
(
y
)
The output is:
tensor([[1, 2, 3],
[0, 5, 6],
[0, 0, 9]])
Example
import
torch
Create a matrix
a
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
Extract the upper triangle above the first diagonal over the main diagonal
y
=
torch.
triu
(
a
,
diagonal
=
1
)
(
y
)
The output is:
tensor([[0, 2, 3],
[0, 0, 6],
[0, 0, 0]])
Example
import
torch
Create a non-square matrix
a
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
Extract the upper triangular part
y
=
torch.
triu
(
a
)
(
y
)
The output is:
tensor([[1, 2, 3],
[0, 5, 6]])