1
$\begingroup$

I have done a lot of variable replacements in order to simplify equation so that it can be solved by mathematica command. After getting the solution I have to go backwards in Replace All. Is there a short cut for this? For example,

r1=ReplaceAll[expr,a->b];
r2=ReplaceAll[r1,c->d];
r3=ReplaceAll[r2,e->f];
r4=ReplaceAll[r3,g->h];
Solution=Solve[r4];
r5=ReplaceAll[Solution,h->g];
r6=ReplaceAll[r5,f->e];
r7=ReplaceAll[r6,d->c];
answer=ReplaceAll[r7,b->a];

Is there a quick way to go backward in ReplaceAll, something like Evaluate (it does not work)?

Thanks in advance.

$\endgroup$
  • $\begingroup$ Please include the definition of expr. $\endgroup$ – Edmund Jun 21 '17 at 3:21
  • 1
    $\begingroup$ Strictly speaking, the replacement like g->h followed by h->g can't be reversed in general because it results in loss of information if the original expression contains both g and h. $\endgroup$ – Alexey Popkov Jun 21 '17 at 11:57
4
$\begingroup$

You could accomplish your replacements by first making a list of replacement rules

rules = {a -> b, c -> d, e -> f, g -> h}

Then you can apply them all in sequence using Fold

replaced = Fold[ ReplaceAll, expr, rules ]

If you need the results of each replacement in turn, you can use FoldList instead

{r1,r2,r3,r4} = FoldList[ ReplaceAll, expr, rules ]

Then you can apply the rules in reverse:

final = Fold[ ReplaceAll, Solve@replaced, Reverse/@rules ]

Note that, depending upon your needs, it may work to simply apply all the rules in one call to ReplaceAll :

replaced2 = expr /. rules
final2 = Solve@replaced2 /. Reverse/@rules
$\endgroup$
  • $\begingroup$ i think you do not need to use a Fold, FoldList or any iteration construct.ReplaceAll will apply all the transformation rules on the expression in a single go. Therefore, in my answer i have avoided using an iteration construct $\endgroup$ – Ali Hashmi Jun 21 '17 at 14:59
  • $\begingroup$ @AliHashmi Yes, that's exactly what I mentioned in the last few lines of my answer. $\endgroup$ – jjc385 Jun 21 '17 at 16:25
2
$\begingroup$
rules = {a->b, c->d, e->f, g->h};
Solve[expr /. rules] /. (Map[Reverse]@rules)
$\endgroup$

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.