# How to get the rank of a matrix in PyTorch?

The rank of a matrix can be obtained using torch.linalg.matrix_rank(). It takes a matrix or a batch of matrices as the input and returns a tensor with rank value(s) of the matrices. torch.linalg module provides us many linear algebra operations.

## Syntax

torch.linalg.matrix_rank(input)

where input is the 2D tensor/matrix or batch of matrices.

## Steps

We could use the following steps to get the rank of a matrix or batch of matrices −

• Import the torch library. Make sure you have it already installed.

import torch

• Create a 2D tensor/matrix or a batch of matrices and print it.

t = torch.tensor([[1.,2.,3.],[4.,5.,6.]])
print("Tensor:", t)
• Compute the rank of the above defined matrix, and optionally assign this value to a new variable.

rank = torch.linalg.matrix_rank(t)

• Print the computed rank of the matrix.

print("Rank:", rank)

## Example 1

The following Python program shows how to find the rank of a matrix in PyTorch −

# import torch library
import torch

# create a 2D Tensor/Matrix
t = torch.rand(4,3)
print("Matrix:", t)

# compute the rank of the matrix
rank = torch.linalg.matrix_rank(t)
print("Rank:", rank)

## Output

Matrix:
tensor([[0.6594, 0.5502, 0.9927],
[0.3542, 0.0738, 0.0039],
[0.7521, 0.9089, 0.7459],
[0.1236, 0.8219, 0.0199]])
Rank: tensor(3)

## Example 2

The following Python program shows how to find the rank of a complex matrix in PyTorch −

# import torch library
import torch

# create a complex Matrix
C = torch.rand(4,3, dtype = torch.cfloat)
print("Matrix:", C)

# compute the rank of above created complex matrix
rank = torch.linalg.matrix_rank(C)
print("Rank:", rank)

## Output

Matrix:
tensor([[0.2830+0.9152j, 0.4017+0.3157j, 0.6843+0.7504j],
[0.5469+0.6831j, 0.5949+0.1112j, 0.1225+0.5372j],
[0.5016+0.2642j, 0.8466+0.5250j, 0.8644+0.6261j],
[0.9070+0.0886j, 0.2665+0.7483j, 0.0226+0.3262j]])
Rank: tensor(3)

## Example 3

The following Python program shows how to compute the ranks of a batch of matrices −

# import torch library
import torch

# create a batch of a batch of 4, 3x2 Matrices
B = torch.rand(4,3,2)
print("Matrix:", B)

# Compute the ranks of the matrices
ranks = torch.linalg.matrix_rank(B)

# print the ranks of matrices
print("Ranks:", ranks)

## Output

Matrix:
tensor([[[0.1332, 0.6924],
[0.7986, 0.3856],
[0.7675, 0.6632]],

[[0.8832, 0.4365],
[0.2731, 0.8355],
[0.8793, 0.0253]],

[[0.4678, 0.7772],
[0.4612, 0.8683],
[0.3522, 0.8857]],

[[0.5602, 0.1209],
[0.2810, 0.0738],
[0.4715, 0.5878]]])
Ranks: tensor([2, 2, 2, 2])