euraad
euraad

Reputation: 2856

How to find the eigenvalues and eigenvectors of a matrix with SymPy?

I want to calculate the eigenvectors x from a system A by using this: A x = λ x

The problem is that I don't know how to solve the eigenvalues by using SymPy. Here is my code. I want to get some values for x1 and x2 from matrix A

from sympy import *
x1, x2, Lambda = symbols('x1 x2 Lambda')
I = eye(2)
A = Matrix([[0, 2], [1, -3]])
equation = Eq(det(Lambda*I-A), 0)
D = solve(equation)
print([N(element, 4) for element in D]) # Eigenvalus in decimal form
print(pretty(D)) # Eigenvalues in exact form

X = Matrix([[x1], [x2]]) # Eigenvectors
T = A*X - D[0]*X # The Ax = %Lambda X with the first %Lambda = D[0]
print(pretty(solve(T, x1, x2)))

Upvotes: 13

Views: 27762

Answers (4)

stansy
stansy

Reputation: 308

You can also use numpy:

from numpy.linalg import eig

B = np.array(A, dtype=np.float32)
display(Matrix(eig(B).eigenvalues), Matrix(eig(B).eigenvectors))

Upvotes: 0

Mohammed
Mohammed

Reputation: 2699

This answer will help you when you all eignvectors, the solution above doesnt always give you all eienvectos for example this matrix A used below

# the matrix
A = Matrix([
    [4, 0, 1],
    [2, 3, 2],
    [1, 0, 4]
])

    sym_eignvects = []
    for tup in sMatrix.eigenvects():
        for v in tup[2]:
            sym_eignvects.append(list(v))

Upvotes: 0

laolux
laolux

Reputation: 1565

sympy has a very convenient way of getting eigenvalues and eigenvectors: sympy-doc

Your example would simply become:

from sympy import *
A = Matrix([[0, 2], [1, -3]])
print(A.eigenvals())  #returns eigenvalues and their algebraic multiplicity
print(A.eigenvects())  #returns eigenvalues, eigenvects

Upvotes: 7

user6655984
user6655984

Reputation:

The methods eigenvals and eigenvects is what one would normally use here.

A.eigenvals() returns {-sqrt(17)/2 - 3/2: 1, -3/2 + sqrt(17)/2: 1} which is a dictionary of eigenvalues and their multiplicities. If you don't care about multiplicities, use list(A.eigenvals().keys()) to get a plain list of eigenvalues.

The output of eigenvects is a bit more complicated, and consists of triples (eigenvalue, multiplicity of this eigenvalue, basis of the eigenspace). Note that the multiplicity is algebraic multiplicity, while the number of eigenvectors returned is the geometric multiplicity, which may be smaller. The eigenvectors are returned as 1-column matrices for some reason...

For your matrix, A.eigenvects() returns the eigenvector [-2/(-sqrt(17)/2 + 3/2), 1] for the eigenvalue -3/2 + sqrt(17)/2, and eigenvector [-2/(3/2 + sqrt(17)/2), 1] for eigenvalue -sqrt(17)/2 - 3/2.

If you want the eigenvectors presented as plain lists of coordinates, the following

[list(tup[2][0]) for tup in A.eigenvects()]

would output [[-2/(-sqrt(17)/2 + 3/2), 1], [-2/(3/2 + sqrt(17)/2), 1]]. (Note this just picks one eigenvector for each eigenvalue, which is not always what you want)

Upvotes: 12

Related Questions