Search code examples
pythonsympylinear-algebrasymbolic-math

Substitute a variable in a Sympy matrix without having the symbol


Some function in my code returns a sympy.Matrix, but not the symbols that were used to create the matrix. I now want to substitute some of its value using its subs() method, but I do not have the symbols. Is there a way other than creating symbols with the same label again and using those?

Some piece of code to recreate the behavior would be the following:

import sympy as sp
x = sp.Symbol('x', real=True)
m = sp.Matrix([[0, x], [0, 0]])
x = 'something_else'
print(m.subs(x, 10))

Solution

  • If you are allowed to modify the code of your function, you could returned the symbols in the order of your liking:

    def func():
        x, y, z = symbols("x, y, z")
        return x, y, z, Matrix([[x, y], [z, 0]])
    

    Otherwise you could extract the symbols from the free_symbol attribute of a Matrix:

    from sympy import *
    x, y, z = symbols("x, y, z")
    M = Matrix([[x, y], [z, 0]])
    list(M.free_symbols)
    # out: [x, z, y]