Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

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

1 Answer 1

up vote 6 down vote accepted

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}}
*)
share|improve this answer
1  
Hey, but that thing is worth lots of $! –  Yves Klett Jan 9 at 17:19
    
@Yves Use Unique["n"] to fix that. –  Mr.Wizard Jan 9 at 17:26
    
@Mr.Wizard Why do you want to fix that? Don't you like "$"? –  belisarius Jan 9 at 17:29
    
Yves complained about "$" so I gave a solution. Also Unique["n"] gives results that match the OP's example. –  Mr.Wizard Jan 9 at 17:32
    
@Mr.Wizard Damn, my understanding was that Yves was trying to buy my answer. –  belisarius Jan 9 at 17:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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