# How to replace multiple variables at once

I would like to make a replacement "c1 C1 -> F1, c2 C2-> F2...." such that the expression like this "c1 C1 c2 C2 c3 C3 c4 C4" becomes "F1 F2 F3 F4".

I used the standard replacement method: c1 C1 c2 C2 c3 C3 c4 C4 /. {c1 C1 ->F1, c2 C2 -> F2, c3 C3-> F3, c4 C4-> F4}. But mathematica only gives "F1 c2 C2 c3 C3 c4 C4", it only replace the first product.

What is the reason this replacement does not work? How could I make such a replacement at once?

Thanks a lot.

• use //. instead of /. – Dr. belisarius Dec 24 '13 at 3:08
• It works! Thanks a lot! In fact, I used /. for the multiple variables replacement before but never have problems. May I ask why this does not work this time? – skippyho Dec 24 '13 at 3:12
• Check out the help files for ReplaceAll and ReplaceRepeated – bill s Dec 24 '13 at 4:49
• Some of the discussion here is related. There are probably other questions where issues related to matching subexpressions of Plus and Times are discussed. – Michael E2 Dec 24 '13 at 5:16

When it's not more complicated than your example, I do the replacement in the form

c1 C1 c2 C2 c3 C3 c4 C4 /. {C1 -> F1 / c1, C2 -> F2 / c2, C3 -> F3 / c3, C4 -> F4 / c4}


with simplified patterns that avoid tricky issues of pattern-matching.

The trouble is that the FullForm of c1 C1 is Times[c1, C1] which on the face of it doesn't exactly match the FullForm of c1 C1 c2 C2 c3 C3 c4 C4, which is

Times[c1, C1, c2, C2, c3, C3, c4, C4]


But the pattern-matcher does match them and replaces only a subsequence of the arguments of Times. But since the Times expression has matched already, further rules are not applied. We're lucky (as users) that it matches once, but unlucky that it doesn't match repeatedly. That's why ReplaceRepeated (//.) works: it keeps applying the rules until there are no more matches. First rule will be applied the first time but not on subsequent tries since it will no longer match; and second on the second try, etc.

• Nice explanation and recommendations! – Dr. belisarius Dec 24 '13 at 13:31
• Thanks a lot for such a nice explanation!! – skippyho Dec 25 '13 at 6:01