2
$\begingroup$

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.

$\endgroup$
  • 3
    $\begingroup$ use //. instead of /. $\endgroup$ – Dr. belisarius Dec 24 '13 at 3:08
  • $\begingroup$ 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? $\endgroup$ – skippyho Dec 24 '13 at 3:12
  • $\begingroup$ Check out the help files for ReplaceAll and ReplaceRepeated $\endgroup$ – bill s Dec 24 '13 at 4:49
  • $\begingroup$ Some of the discussion here is related. There are probably other questions where issues related to matching subexpressions of Plus and Times are discussed. $\endgroup$ – Michael E2 Dec 24 '13 at 5:16
6
$\begingroup$

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.

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

protected by xzczd Sep 17 at 14:39

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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