I have an expression of the form:


I would like to replace each of the variables n with a different variable, like:


The order doesn't matter, but it matters that each n have a different name.

I can find the positions of the n's simply with:


and this returns a list of positions {{1}, {2, 1}, {5, 1}} as expected. I would then like to run through this list and make replacements in those positions. However, I don't want to have to do this by hand. Clearly I could do:


but the real expression I have is many thousands of times larger.

I have tried using:

Apply[Part, Join[{expr}, pos[[3]]]]=n2

which would allow be to do this in a loop, or functionally, but this doesn't alter the element of the expression as I would like. I have tried playing with Hold in various places but it doesn't seem to work.

Anything simple that I am missing?

  • 5
    $\begingroup$ expr /. n :> Unique@n $\endgroup$ – Dr. belisarius Jan 9 '14 at 16:30
  • 1
    $\begingroup$ expr = x + y + n + Sin[n] + n^2; j = 0; expr /. n :> (j++; nn[j]) $\endgroup$ – Daniel Lichtblau Jan 9 '14 at 16:32
  • 1
    $\begingroup$ @DanielLichtblau the reason is that procedural code gets a penalty :D HNY BTW $\endgroup$ – Yves Klett Jan 9 '14 at 16:35
  • 1
    $\begingroup$ @Yves Klett I meant "beaten" in terms of "first to appear". But I agree his is the better method. Not faulting mine specifically for procedural usage but more because it has an unscoped global. $\endgroup$ – Daniel Lichtblau Jan 9 '14 at 16:40
  • 1
    $\begingroup$ @belisarius answer, answer, ANSWER! $\endgroup$ – Yves Klett Jan 9 '14 at 16:46

You may do something like:

expr = x + y + n + Sin[n] + n^2; 
{newExpr, {newVars}} = Reap[expr /. n :> Sow[Unique@n]];
{newExpr, newVars}
 {n$9881 + n$9882^2 + x + y + Sin[n$9883], {n$9881, n$9882, n$9883}}
  • 1
    $\begingroup$ Hey, but that thing is worth lots of $! $\endgroup$ – Yves Klett Jan 9 '14 at 17:19
  • $\begingroup$ @Yves Use Unique["n"] to fix that. $\endgroup$ – Mr.Wizard Jan 9 '14 at 17:26
  • $\begingroup$ @Mr.Wizard Why do you want to fix that? Don't you like "$"? $\endgroup$ – Dr. belisarius Jan 9 '14 at 17:29
  • $\begingroup$ Yves complained about "$" so I gave a solution. Also Unique["n"] gives results that match the OP's example. $\endgroup$ – Mr.Wizard Jan 9 '14 at 17:32
  • $\begingroup$ @Mr.Wizard Damn, my understanding was that Yves was trying to buy my answer. $\endgroup$ – Dr. belisarius Jan 9 '14 at 17:35

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.