0

subs (from sympy library in Python) does not replace a subexpression in all cases except simple ones. MATLAB copes with this task perfectly. Is it possible to somehow achieve the same result as in MATLAB?

Sympy

sympy

MATLAB

matlab

matheburg
  • 2,097
  • 1
  • 19
  • 46
  • 2
    You better post your code as text instead of images. – matheburg Jan 28 '23 at 04:03
  • I love this question, but I fear the answer is that `sympy` is basically only capable of substituting expressions as present in the current representation. See, e.g., https://stackoverflow.com/questions/34633262/sympy-substitute-mathematical-expression. I guess you have to contribute to [`sympy`](https://github.com/sympy/sympy) to improve it ;) – matheburg Jan 28 '23 at 04:13
  • You can use `e.subs(x, z - y)` – Oscar Benjamin Jan 28 '23 at 11:59
  • Print the `f` before the subs. `sympy` expanded it to the [3] form on creation, so the `x+y` expression doesn't exist in `f`. – hpaulj Jan 28 '23 at 16:54
  • The substitution works in `g = parse_expr('-1/(2*(x+y))',evaluate=False)` because it does not expand the multiplication. – hpaulj Jan 28 '23 at 16:58

1 Answers1

0

This fails because the product 2*(x + y) automatically expands to the sum of 2x + 2*y, as @hpaulj points out. And @oscarbenjamin points out that re-arranging your substitution so it targets only an atomic part of the expression you desire to replace will work.

In addition, if you backsubstitute to restore the original atom you will see if the substitution was not able to be fully done while retaining the original variables:

>>> f = (x + y)**2 + 1/(4*x + 4*y + sin(2*x + 2*y))
>>> (f+x).subs(x,z-y).subs(y,z-x)
x + z**2 + 1/(4*z + sin(2*z))
smichr
  • 16,948
  • 2
  • 27
  • 34