Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Return matrix rank of array using Singular Value Decomposition method in Python
To return the matrix rank of an array using the Singular Value Decomposition (SVD) method, use the numpy.linalg.matrix_rank() method in Python. The rank of a matrix represents the number of linearly independent rows or columns, calculated as the count of singular values greater than a specified tolerance.
Syntax
numpy.linalg.matrix_rank(A, tol=None, hermitian=False)
Parameters
A: Input vector or stack of matrices whose rank needs to be computed.
tol: Threshold below which SVD values are considered zero. If None, it's automatically set to S.max() * max(M, N) * eps, where S contains singular values and eps is the machine precision.
hermitian: If True, assumes the matrix is Hermitian (complex conjugate transpose equals itself), enabling more efficient computation. Defaults to False.
Example
Let's compute the matrix rank of an identity matrix using SVD ?
import numpy as np
from numpy.linalg import matrix_rank
# Create a 5x5 identity matrix
arr = np.eye(5)
# Display the array
print("Our Array...")
print(arr)
# Check dimensions and properties
print("\nDimensions:", arr.ndim)
print("Datatype:", arr.dtype)
print("Shape:", arr.shape)
# Calculate matrix rank using SVD
rank = matrix_rank(arr)
print("\nMatrix Rank:", rank)
Our Array... [[1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.]] Dimensions: 2 Datatype: float64 Shape: (5, 5) Matrix Rank: 5
Working with Different Matrices
Let's see how matrix rank varies for different types of matrices ?
import numpy as np
from numpy.linalg import matrix_rank
# Create different matrices
identity = np.eye(3)
singular = np.array([[1, 2, 3], [2, 4, 6], [1, 2, 3]]) # Rank deficient
random_matrix = np.random.rand(3, 3)
print("Identity Matrix Rank:", matrix_rank(identity))
print("Singular Matrix Rank:", matrix_rank(singular))
print("Random Matrix Rank:", matrix_rank(random_matrix))
# Using custom tolerance
print("Singular Matrix Rank (tol=0.1):", matrix_rank(singular, tol=0.1))
Identity Matrix Rank: 3 Singular Matrix Rank: 1 Random Matrix Rank: 3 Singular Matrix Rank (tol=0.1): 1
Key Points
- Identity matrices have full rank equal to their dimensions
- Singular (rank-deficient) matrices have rank less than their dimensions
- The tolerance parameter affects rank calculation for matrices with small singular values
- SVD provides numerical stability for rank computation
Conclusion
The numpy.linalg.matrix_rank() function efficiently computes matrix rank using SVD. Identity matrices have full rank, while singular matrices are rank-deficient. Adjusting the tolerance parameter helps handle numerical precision issues.
