I'm trying to replace variables outside of certain functions. More precisely, in the standard ones like Sin substitution should work while in undefined BC and u (and all their derivatives) should not, and it always should work outside of any functions. I checked 71691 and 33025 but found no suitable advice.

From this:

-x1 BC[x1, x2, x3, t1, t2] Sin[x2]^2 u[x1, x2, x3, t1, t2] + D[BC[x1, x2, x3, t1, t2],x1,x1]

With a substitution like {x1->x1[t1,t2], x2->x2[t1,t2]} I would like to get this:

-x1[t1,t2] BC[x1, x2, x3, t1, t2] Sin[x2[t1,t2]]^2 u[x1, x2, x3, t1, t2] + D[BC[x1, x2, x3, t1, t2],x1,x1]

Derivative is of course written with upper indices in the code. I'm trying (according to the previous answers) this:

EQ = -x1 BC[x1, x2, x3, t1, t2] Sin[x2]^2 u[x1, x2, x3, t1, t2] + D[BC[x1, x2, x3, t1, t2],x1,x1];
EQPOS = Join[Position[EQ, BC[__]], Position[EQ, u[__]]];
EQPOSED = MapAt[ReplaceAll[#, {x1 -> EX1, x2 -> EX2, x3 -> EX3}] &, EQ, EQPOS] /. {x1 -> x1[t1, t2], x2 -> x2[t1, t2], x3 -> x3[t1, t2]} /. {EX1 -> x1, EX2 -> x2, EX3 -> x3}

As you can see this method fails to work with derivatives.

  • 2
    $\begingroup$ Perhaps you should use a pattern that can catch derivatives: Join[Position[EQ, BC[__] | Derivative[__][BC][__]], Position[EQ, u[__] | Derivative[__][u][__]]] $\endgroup$ Mar 28, 2019 at 13:18

1 Answer 1


Make use of the execution order in a rule replacement list: once a part of an expression has been matched and replaced, it then remains untouched by subsequent replacement rules. With this trick we can make sure that BC and u are replaced with themselves first (so nothing happens to them and their arguments), and everything else is replaced according to the rules you give after that:

EQ = -x1*BC[x1,x2,x3,t1,t2]*Sin[x2]^2*u[x1,x2,x3,t1,t2] + D[BC[x1,x2,x3,t1,t2],x1,x1];

EQ /. {z : Through[(Identity | Derivative[__])[BC | u]][__] -> z, 
       x1 -> x1[t1, t2], x2 -> x2[t1, t2]}

-BC[x1, x2, x3, t1, t2]*Sin[x2[t1, t2]]^2*u[x1, x2, x3, t1, t2]*x1[t1, t2] + Derivative[2, 0, 0, 0, 0][BC][x1, x2, x3, t1, t2]

See here for how to construct the above z pattern that matches BC[__], u[__], as well as all of their derivatives.


Your Answer

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

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