
How to calculate the rank of a matrix in NumPy (Python)
Using linalg module in numpy, the rank of a matrix is easily calculated.
import numpy as np
from numpy import linalg
A = np.array([[1, 2], [3, 4]])
B = np.array([[1, 2], [1, 2]])
C = np.array([[0, 0], [0, 0]])
D = np.array([[0, 0, 1], [1, 0, 0]])
a = linalg.matrix_rank(A)
b = linalg.matrix_rank(B)
c = linalg.matrix_rank(C)
d = linalg.matrix_rank(D)
print(a) # 2
print(b) # 1
print(c) # 0
print(d) # 2
The rank of a matrix is equal to the dimension of the linear spaces generated by the matrix's rows (or columns).
The rank of B is 1 because (1, 2)
and (1, 2)
generate 1 dimension space (line).
Comments
Powered by Markdown