Search code examples
pythonfunctioneigenvalueeigenvector

Creating a function that returns a dictionary with eigenvalue and eigenvector


I'm trying to create a function in Python that returns a dictionary with an eigenvector and it's corresponding eigenvalue:

This is my working code so far:

def eigenvectors(a):
    b = np.matrix(a)
    dicto = {}
    for i in b:
        dicto.append(b)
    return dicto

eigenvectors('1,2,3')

I don't think I'm going about this the right way. Basically, my parameter I'm trying to define is a matrix where no matter what matrix I put in the function, I will be able to get back the eigenvector and eigenvalue associated with it.

If anyone could help me out, I would really appreciate it. I feel like I have the concept down but I'm just having a hard time putting the function together.


Solution

  • Does numpy.linalg.eig helps? https://numpy.org/doc/stable/reference/generated/numpy.linalg.eig.html

    If you want it exclusively as a dict you can simply use zip:

    a = np.array([
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ])
    
    def eigenvectors(a):
        values, vectors = np.linalg.eig(a)
        return dict(zip(values, vectors))
    
    eigenvectors(a)