I know this question has been asked multiple times before but unfortunately it seems like I'm too dumb to understand what is really going on and how to solve this.
Anyway, I want to resubstitute certain parts of an equation but also on all levels of that equation. My minified problem looks like this:
G = 4/3 x a - 4/3 y b - z^2; rules = {4/3 x -> r1, 4/3 y -> r2, z^2 -> r3}; t1 = ReplaceAll[G, rules] t2 = ReplaceRepeated[G, rules] t3 = Replace[G, rules, All] t4 = Replace[G, rules, {0, Infinity}] For completion, the FullForm of G looks like this:
Plus[Times[Rational[4, 3], a, x], Times[Rational[-4, 3], b, y], Times[-1, Power[z, 2]]] If I understand it right, then ReplaceAll will replace my substitutions but only on level 0. ReplaceRepeated has the same problem and Replace, even when specifying levelspec won't work either. This is the output of the above test:
(* t1 *) a r1 - r3 - (4 b y)/3 (* t2 *) a r1 - r3 - (4 b y)/3 (* t3 *) -r3 + (4 a x)/3 - (4 b y)/3 (* t4 *) -r3 + (4 a x)/3 - (4 b y)/3 I can see that in the second term (4/3 y) can't be replaced because Mathematica treats it as Times[Rational[-4, 3], b, y] and the - does not correspond to the replacement rule. I have no clue why both cases of Replace don't work at all...
Is there a way to apply these replacement rules to any level of the equation? Can someone explain me what is going on here?
ReplaceAll: "ReplaceAll looks at each part of expr, tries all the rules on it, and then goes on to the next part of expr. The first rule that applies to a particular part is used; no further rules are tried on that part or on any of its subparts." $\endgroup$