Diagonalize symbolic matrix

丶灬走出姿态 提交于 2019-12-13 13:25:45

问题


I need to diagonalize a symbolic matrix with python. In Mathematica it can be done easily, but when using the module numpy.linalg I get problems.

For concreteness, consider the matrix

[[2, x], [x, 3]]

where x is a symbolic variable. I guess I get problems because the numpy package is provided for numerical computations, not symbolic, but I cannot find how to do it with sympy.


回答1:


You can compute it from the eigenvalues, but there is actually a method that will do it for you, diagonalize

In [13]: M.diagonalize()
Out[13]:
⎛                                        ⎡     __________                       ⎤⎞
⎜                                        ⎢    ╱    2                            ⎥⎟
⎜⎡      -2⋅x                2⋅x       ⎤  ⎢  ╲╱  4⋅x  + 1    5                   ⎥⎟
⎜⎢─────────────────  ─────────────────⎥, ⎢- ───────────── + ─          0        ⎥⎟
⎜⎢   __________         __________    ⎥  ⎢        2         2                   ⎥⎟
⎜⎢  ╱    2             ╱    2         ⎥  ⎢                                      ⎥⎟
⎜⎢╲╱  4⋅x  + 1  - 1  ╲╱  4⋅x  + 1  + 1⎥  ⎢                        __________    ⎥⎟
⎜⎢                                    ⎥  ⎢                       ╱    2         ⎥⎟
⎜⎣        1                  1        ⎦  ⎢                     ╲╱  4⋅x  + 1    5⎥⎟
⎜                                        ⎢         0           ───────────── + ─⎥⎟
⎝                                        ⎣                           2         2⎦⎠

M.diagonalize() returns a pair of matrices (P, D) such that M = P*D*P**-1. If it can't compute enough eigenvalues, either because the matrix is not diagonalizable or because solve() can't find all the roots of the characteristic polynomial, it will raise MatrixError.

See also this section of the SymPy tutorial.




回答2:


Assuming the matrix is diagonalizable, you can get the eigenvectors and eigenvalues by

from sympy import *
x = Symbol('x')
M = Matrix([[2,x],[x,3]])
print M.eigenvects()
print M.eigenvals()

Giving:

[(-sqrt(4*x**2 + 1)/2 + 5/2, 1, [[-x/(sqrt(4*x**2 + 1)/2 - 1/2)]
[                            1]]), (sqrt(4*x**2 + 1)/2 + 5/2, 1, [[-x/(-sqrt(4*x**2 + 1)/2 - 1/2)]
[                             1]])]
{sqrt(4*x**2 + 1)/2 + 5/2: 1, -sqrt(4*x**2 + 1)/2 + 5/2: 1}

You should check out the documentation, there are many other decompositions listed there.

Note that not every matrix is diagonalizable, but you can put every matrix into Jordan Normal Form using the sympy command .jordan_form.



来源:https://stackoverflow.com/questions/18702271/diagonalize-symbolic-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!