Search code examples
pythonsympysymbolic-math

Replacing a sympy matrix symbol in a sum of its elements


Consider an arbitrary expression which contains a sum of elements of a Matrix symbol:

>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A',3,3)
>>> expr = A[1,2]+A[0,1]+A[2,0]

Is it possible to simply replace the matrix symbol A, with a numerical matrix T?

I assumed using subs would be sufficient, but this does not seem to be the case.

>>> import numpy as np
>>> T = np.arange(9).reshape((3,3))
>>> print(expr.subs(A,T))
A[0, 1] + A[1, 2] + A[2, 0]

Solution

  • The problem is that you are using a numpy array rather than a SymPy Matrix:

    In [9]: from sympy import Matrix
    
    In [10]: T = Matrix(np.arange(9).reshape(3, 3))
    
    In [11]: expr
    Out[11]: A₀₁ + A₁₂ + A₂₀
    
    In [12]: expr.subs(A, T)
    Out[12]: 12