pythonnumpy

Error in keyword argument for matrix_rank


I want to compute the rank of a matrix, and introduce a certain relative tolerance to take into account the numerical errors. I use the following code :

    A = np.random.randn(n,n)
    r = np.linalg.matrix_rank(A, rtol = 1e-5)

but i get the following error : 'TypeError: matrix_rank() got an unexpected keyword argument 'rtol''

As written here : https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_rank.html, I don't understand why it doesn't work.


Solution

  • your version of NumPy does not support the rtol keyword in the np.linalg.matrix_rank so you can upgrade it or use this code

    import numpy as np
    
    A = np.random.randn(4, 4)
    tol = 1e-5
    u, s, vh = np.linalg.svd(A) 
    rank = np.sum(s > tol * np.max(s)) 
    print("Rank:", rank)