0
0
NumpyHow-ToBeginner ยท 3 min read

How to Find Rank of Matrix Using NumPy in Python

You can find the rank of a matrix in NumPy using the numpy.linalg.matrix_rank() function. It returns the number of linearly independent rows or columns in the matrix.
๐Ÿ“

Syntax

The function to find the rank of a matrix is numpy.linalg.matrix_rank(M, tol=None).

  • M: The input matrix (2D array or higher-dimensional array).
  • tol: Optional threshold to decide when a singular value is considered zero (default is None, which uses a machine precision based value).

The function returns an integer representing the rank of the matrix.

python
import numpy as np

rank = np.linalg.matrix_rank(M, tol=None)
๐Ÿ’ป

Example

This example shows how to find the rank of a 2D matrix using numpy.linalg.matrix_rank(). The matrix has some dependent rows, so the rank is less than the number of rows.

python
import numpy as np

# Define a 3x3 matrix with dependent rows
M = np.array([[1, 2, 3],
              [4, 5, 6],
              [2, 4, 6]])

# Calculate the rank
rank = np.linalg.matrix_rank(M)
print("Rank of the matrix:", rank)
Output
Rank of the matrix: 2
โš ๏ธ

Common Pitfalls

One common mistake is to assume the rank is always the smaller dimension of the matrix. If rows or columns are linearly dependent, the rank is less.

Another pitfall is ignoring the tol parameter. Very small singular values might be treated as zero or not depending on tol, affecting the rank.

Also, passing a 1D array instead of a 2D matrix will give incorrect results.

python
import numpy as np

# 1D array
vec = np.array([1, 2, 3])
rank_1d = np.linalg.matrix_rank(vec)
print("Rank of 1D array:", rank_1d)

# Reshape to 2D
vec_2d = vec.reshape(1, -1)
rank_2d = np.linalg.matrix_rank(vec_2d)
print("Rank of reshaped 2D array:", rank_2d)
Output
Rank of 1D array: 1 Rank of reshaped 2D array: 1
๐Ÿ“Š

Quick Reference

FunctionDescription
numpy.linalg.matrix_rank(M, tol=None)Returns the rank of matrix M
MInput matrix (2D array)
tolThreshold for small singular values (optional)
โœ…

Key Takeaways

Use numpy.linalg.matrix_rank() to find the rank of a matrix easily.
The rank is the count of linearly independent rows or columns.
Ensure your input is a 2D array to get correct results.
The tol parameter controls sensitivity to small singular values.
Dependent rows or columns reduce the matrix rank below its dimensions.