Search code examples
pythonnumpymatrixeigenvalue

Whats the fastest way to calculate the eigenvalues and eigenvectors of a 2D real symetrical Matrix


Is there a faster way to calculate the eigenvalues and eigenvectors of a 2D real symetrical Matrix besides:

N = 10101
S = np.random.random((N,N))
S = (S + S.T)/2

eigenValues, eigenVectors = np.linalg.eig(S)
idx = eigenValues.argsort()[::-1]

eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]

This take too long for me


Solution

  • I would use np.linalg.eigh since it's designed for real symmetric matrices and it will use a special algorithm. Another benefit is that the returned eigenvalues are sorted in ascending order, so you will not need to use argsort().

    Speed comparison with N = 1010 so I'm not waiting around forever:

    eig_vals, eig_vects = np.linalg.eig(S)
    # 628 ms ± 45.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    eig_vals, eig_vects = np.linalg.eigh(S)
    # 89.1 ms ± 2.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    from scipy import linalg as la
    eig_vals, eig_vects = la.eigh(S)
    # 346 ms ± 10.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    

    np.linalg.eigh is the fastest by far.