# Match and replace subexpression

I would like to replace the expresion $(n1-1)$ to $z1$ in following:

2*n1*p[n1-1,n2]


2*(z1+1)*p[z1,n2]

I have tried Replace, ReplaceAll, /., //. but nothing seems to be working. Only part inside $p[n1-1, n2]$ is replaced. Can anyone help me with this?

• (* stuff *) /. n1 -> z1 +1 doesn't do what you want? – J. M.'s ennui Apr 8 '13 at 12:58

If you type:

2 n1 p[n1-1, n2] /. {n1 -> z1 +1}


2 (1 + z1) p[z1, n2]


This is shorthand for the function:

ReplaceAll[2 n1 p[n1 - 1, n2], n1 -> z1+1]


which explicitly uses the rule (in the second argument) to change the first argumemnt.

• Ah strange asterixes appear in your answer. I figured I'd (propose to) edit them, but you made an edit as well in the meantime. Oh well, please fix the asterixes :). – Jacob Akkerboom Apr 8 '13 at 13:24
• thanks Jacob -- I don't know where they came from... – bill s Apr 8 '13 at 13:27
• No problem, I think they came from the original problem statement, that has now been fixed by Istvan Zachar :). Hm.. I think Maria was trying to also replace the n1 that appears outside the function p, so I think this is probably not what she wants.. – Jacob Akkerboom Apr 8 '13 at 13:30
• I just realized that and changed it. But now I realize this is exactly what JM suggested... sorry JM.. I'm happy to delete and give to you... – bill s Apr 8 '13 at 13:33
• Yesterday I posted the silliest answer only to delete it a minute later, I can relate :P – Jacob Akkerboom Apr 8 '13 at 13:37

If $n1$ is set initially, when any function that contains this variable is entered, the conversion will be automatic.

n1 = z1 + 1;
2*n1*p[n1 - 1, n2]