PyTorch torch.linalg.matrix_rank function
PyTorch torch reference manual
torch.linalg.matrix_rank is a function in PyTorch's linear algebra module used to compute the rank of a matrix. The rank of a matrix is the number of linearly independent rows or columns in the matrix.
Function definition
torch.linalg.matrix_rank(A, tol=None, hermitian=False, out=None)
Parameters:
A(Tensor): Input matrix.tol(float, optional): Singular value threshold.hermitian(bool, optional): If True, the matrix is considered Hermitian (symmetric). Defaults to False.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: Returns the rank of the matrix.
Usage examples
Example
import
torch
Create a full-rank matrix
A
=
torch.
tensor
(
[
[
1.0
,
2.0
,
3.0
]
,
[
4.0
,
5.0
,
6.0
]
,
[
7.0
,
8.0
,
9.0
]
]
)
Compute the matrix rank
rank
=
torch.
linalg
.
matrix_rank
(
A
)
(
"Matrix A:"
)
(
A
)
(
"Matrix rank:"
,
rank
)
The output is:
矩阵 A:
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
矩阵的秩: tensor(2)
Example - full-rank matrix
import
torch
Create a full-rank matrix
B
=
torch.
tensor
(
[
[
1.0
,
2.0
]
,
[
3.0
,
4.0
]
]
)
rank_B
=
torch.
linalg
.
matrix_rank
(
B
)
(
"Matrix B:"
)
(
B
)
(
"Matrix rank:"
,
rank_B
)