Search code examples
pythonnumpymatrixeigenvalueeigenvector

Eigen values and vectors calculation error in python


I'm trying to obtain the eigenvectors and values of any matrix 'X' in a specific format. I used the linalg function to get the eigen pairs but the expected output format is different from my result. For example, v and e denote the eigenvalues and eigenvectors. v1 = 1, e1 = [1,0,0], v2 = 2, e2 = [0,1,0], v3 = 3, e3 = [0,0,1].

So in this example, the eigen pairs of matrix X should be Ep =[(1, [1,0,0]) (2, [0,1,0]), (3, [0,0,1])]. Here P[0] represents the first eigen pair (1,[1,0,0]), where the eigenvalue is 1, and the eigenvector is [1,0,0].

Can you please help me code this part further?

e,v = np.linalg.eigh(X)

Solution

  • np.linalg.eigh

    First, one should note that np.linalg.eigh calculates the eigenvalues of a Hermitian matrix -- this will not apply for all matrices. If you want to calculate the eigenvalues of any matrix X you should probably switch to something like np.linalg.eig:

    import numpy as np
    
    L = np.diag([1,2,3])
    V = np.vstack(([1,0,0],[0,1,0],[0,0,1]))
    
    # X = V@L@V.T (eigendecomposition)
    X = V@L@V.T
    
    w,v = np.linalg.eig(X)
    assert (np.diag(w) == L).all()
    assert (v == V).all()
    

    Eigenpairs

    To construct the eigenpairs, just use some list comprehension:

    import numpy as np
    
    # X = V@L@V.T (eigendecomposition)
    X = np.diag([1,2,3])
    
    w,v = np.linalg.eig(X)
    
    Ep = [(val,vec.tolist()) for val,vec in zip(w,v)]
    

    Enjoy!