Sympy Function substitution

Viewed 508

I use things like

x = Function('x',real=True)(t)

which gives x(t) as function variables in all my calculations. I can now differentiate with respect to time, solve (not nonlinsolve or solveset, because they cannot subs these functions) and so on.

However, I want to export my results to MATLAB. So I need the (t) gone. I can fill a dict with d = {x(t):x}, but I think there is a more elegant way to do this for all Functions, like y(t),z(t),...

My desired result is for the input

expr = x(t)-y(t)
output = x-y

where x and y can be "Function" as known to Sympy, but there shall not be (t) in the output. And I do want to avoid introducing all my variables again without the dependence on time!

1 Answers

Here is a loop that walks through the expression tree and replaces any function whose argument is t by a symbol matching the name of that function. The substitutions are made in another copy of the expression, to avoid modifying the expression we are walking through.

Example: if expr is x(t) - y(t), then expr1 is x - y.

expr1 = expr
for f in preorder_traversal(expr):
  if f.args == (t,):
    expr1 = expr1.subs(f, Symbol(str(f.func)))
print(expr1)
Related