1
$\begingroup$

In order to make my question clear, I would like to use a simple expression as an toy example.

Suppose we have an expression, which is,

f = a + 2*b + c

Now I want to replace sub-expression (a+b) with term1, and (b+c) with term2, so that I can obtain the result like

f = term1 + term2

However, I tried functions Replace and ReplaceAll in Mathematica and the results are

[in] f = Replace[f, {(a + b) -> term1, (b + c) -> term2}]
[out] f = a + 2b + c
[in] f = ReplaceAll[f, {(a + b) -> term1, (b + c) -> term2}]
[out] f = a +2b + c

which does not make any changes.

So I was wondering if choose the wrong functions? Or there are some other tricks can be used to achieve this goal.

$\endgroup$
4
$\begingroup$

Simplify has an optional second argument which instructs Simplify to consider this additional information during the simplification process. This can help when the replacement you want is simpler than what you have.

f = a + 2*b + c;
Simplify[f,{a+b==term1,b+c==term2}]

instantly gives you

term1+term2
$\endgroup$
1
$\begingroup$

Try this:

f = a + 2*b + c;
f /. {a -> term1 - b, c -> term2 - b}

(* term1 + term2 *)

Have fun!

$\endgroup$
  • $\begingroup$ This way is tricky but useful! $\endgroup$ – Yuejiang_Li Oct 11 at 2:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.