torch.linalg.matrix_rank(A, tol=None, hermitian=False, *, out=None) → Tensor

Computes the numerical rank of a matrix.

The matrix rank is computed as the number of singular values (or eigenvalues in absolute value when hermitian= True) that are greater than the specified tol threshold.

Supports input of float, double, cfloat and cdouble dtypes. Also supports batches of matrices, and if A is a batch of matrices then the output has the same batch dimensions.

If hermitian= True, A is assumed to be Hermitian if complex or symmetric if real, but this is not checked internally. Instead, just the lower triangular part of the matrix is used in the computations.

If tol is not specified and A is a matrix of dimensions (m, n), the tolerance is set to be

tol=σ1max(m,n)ε\text{tol} = \sigma_1 \max(m, n) \varepsilon

where σ1\sigma_1 is the largest singular value (or eigenvalue in absolute value when hermitian= True), and ε\varepsilon is the epsilon value for the dtype of A (see torch.finfo). If A is a batch of matrices, tol is computed this way for every element of the batch.


The matrix rank is computed using singular value decomposition torch.linalg.svd() if hermitian= False (default) and the eigenvalue decomposition torch.linalg.eigvalsh() when hermitian= True. When inputs are on a CUDA device, this function synchronizes that device with the CPU.

  • A (Tensor) – tensor of shape (*, m, n) where * is zero or more batch dimensions.

  • tol (float, Tensor, optional) – the tolerance value. See above for the value it takes when None. Default: None.

  • hermitian (bool, optional) – indicates whether A is Hermitian if complex or symmetric if real. Default: False.

Keyword Arguments

out (Tensor, optional) – output tensor. Ignored if None. Default: None.


>>> a = torch.eye(10)
>>> torch.linalg.matrix_rank(a)
>>> b = torch.eye(10)
>>> b[0, 0] = 0
>>> torch.linalg.matrix_rank(b)

>>> a = torch.randn(4, 3, 2)
>>> torch.linalg.matrix_rank(a)
tensor([2, 2, 2, 2])

>>> a = torch.randn(2, 4, 2, 3)
>>> torch.linalg.matrix_rank(a)
tensor([[2, 2, 2, 2],
        [2, 2, 2, 2]])

>>> a = torch.randn(2, 4, 3, 3, dtype=torch.complex64)
>>> torch.linalg.matrix_rank(a)
tensor([[3, 3, 3, 3],
        [3, 3, 3, 3]])
>>> torch.linalg.matrix_rank(a, hermitian=True)
tensor([[3, 3, 3, 3],
        [3, 3, 3, 3]])
>>> torch.linalg.matrix_rank(a, tol=1.0)
tensor([[3, 2, 2, 2],
        [1, 2, 1, 2]])
>>> torch.linalg.matrix_rank(a, tol=1.0, hermitian=True)
tensor([[2, 2, 2, 1],
        [1, 2, 2, 2]])


Access comprehensive developer documentation for PyTorch

View Docs


Get in-depth tutorials for beginners and advanced developers

View Tutorials


Find development resources and get your questions answered

View Resources