3
$\begingroup$

I have an expression of the form:

expr=x+y+n+Sin[n]+n^2

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

x+y+n1+Sin[n2]+n3^2

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:

pos=Position[expr,n]

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:

expr[[5,1]]=n3

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?

$\endgroup$
8
  • 5
    $\begingroup$ expr /. n :> Unique@n $\endgroup$ Jan 9, 2014 at 16:30
  • 1
    $\begingroup$ expr = x + y + n + Sin[n] + n^2; j = 0; expr /. n :> (j++; nn[j]) $\endgroup$ Jan 9, 2014 at 16:32
  • 1
    $\begingroup$ @DanielLichtblau the reason is that procedural code gets a penalty :D HNY BTW $\endgroup$
    – Yves Klett
    Jan 9, 2014 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$ Jan 9, 2014 at 16:40
  • 1
    $\begingroup$ @belisarius answer, answer, ANSWER! $\endgroup$
    – Yves Klett
    Jan 9, 2014 at 16:46

1 Answer 1

6
$\begingroup$

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}}
*)
$\endgroup$
7
  • 1
    $\begingroup$ Hey, but that thing is worth lots of $! $\endgroup$
    – Yves Klett
    Jan 9, 2014 at 17:19
  • $\begingroup$ @Yves Use Unique["n"] to fix that. $\endgroup$
    – Mr.Wizard
    Jan 9, 2014 at 17:26
  • $\begingroup$ @Mr.Wizard Why do you want to fix that? Don't you like "$"? $\endgroup$ Jan 9, 2014 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, 2014 at 17:32
  • $\begingroup$ @Mr.Wizard Damn, my understanding was that Yves was trying to buy my answer. $\endgroup$ Jan 9, 2014 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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