Search code examples
pythonnumpymatrixnumerical-methods

Finding eigenvalues of a matrix with unknown variables using numpy.linalg.eig


As an example, I have the following matrix:

$$\begin{bmatrix}a+1&1\1&1\end{bmatrix}$$

I would like to find the eigenvalue of the matrix with python. This is my attempt:

arr = np.array( [[ a+1, 1],
             [ 1, 1]] )
print(np.linalg.eig(arr))

Obviously, python tells me that a is not defined. But I dont want to define a. a should just be a variable, and I want the eigenvalues to be expressed by a.

Any ideas?

Kind regards,

Zebraboard


Solution

  • ddejohn is right. What you want is a symbolic operation so use sympy:

    from sympy import var, Matrix
    
    var('a')
    arr = Matrix( [[ a+1, 1],
                 [ 1, 1]] )
    
    arr.eigenvals()
    

    gives

    {a/2 - sqrt(a**2 + 4)/2 + 1: 1, a/2 + sqrt(a**2 + 4)/2 + 1: 1}