Search code examples
matlabsymbolic-math

Rewrite a symbolic expression in terms of a specific subexpression


I need to rewrite a symbolic expression in terms of a specific subexpression.

Consider the following scenario:

  • expression f with 2 variables a, b
  • subexpression c = a / b

    syms a b c
    f = b / (a + b) % = 1 / (1 + a/b) = 1 / (1 + c) <- what I need
    

Is there a way to achieve this?

Edit:

The step from 1 / (1 + a/b) to 1 / (1 + c) can be achieved by calling

subs(1 / (1 + a/b),a/b,c)

So a better formulated question is:

Is there a way to tell MATLAB to 'simplify' b / (a + b) into 1 / (1 + a/b)?

Just calling simplify(b / (a + b) makes no difference.


Solution

  • Simplification to your desired form is not automatically guaranteed, and in my experience, isn't likely to be achieved directly through simplify-ing as I've noticed simplification rules prefer rational polynomial functions. However, if you know the proper reducing ratio, you can substitute and simplify

    >> syms a b c
    >> f = b / (a + b);
    >> simplify(subs(f,a,c*b))
    ans =
    1/(c + 1)
    
    >> simplify(subs(f,b,a/c))
    ans =
    1/(c + 1)
    

    And then re-substitute without simplification, if desired:

    >> subs(simplify(subs(f,a,c*b)),c,a/b)
    ans =
    1/(a/b + 1)
    
    >> subs(simplify(subs(f,b,a/c)),c,a/b)
    ans =
    1/(a/b + 1)