1
$\begingroup$

Suppose I have the expression:

expr = U''[x] + U'[x]

I would like to be able to write an abstract replacement rule so that I can transform the above expression to:

u2 + u1

I was hoping that the replacement rule:

U''[x] + U'[x] /. Derivative[n_][U][x]->StringJoin["u",ToString[n]]

would work. However, this disappointingly uses a literal n, and not a variable n:

U''[x] + U'[x] /. Derivative[n_][U][x]->StringJoin["u",ToString[n]]
(* 2 un *)

I suspect I'm close with my solution and I need to use some kind of # and & method but I still do not fully understand those functions.

Any help would be appreciated.

$\endgroup$
2
  • 1
    $\begingroup$ (dexpr = U''[x] + U'[x]) // FullForm and try: dexpr /. Derivative[x_][f_][v_] :> ToLowerCase@ToString[f] <> ToString[x] $\endgroup$
    – Syed
    May 4, 2022 at 17:53
  • $\begingroup$ @Syed ah yes that works. I always forget about the delayed replace. Using :> in my example also makes the replacement works as desired. $\endgroup$
    – akozi
    May 4, 2022 at 17:56

1 Answer 1

1
$\begingroup$

It is generally easier to deal with indexed variables and to format them for display in any desired manner.

expr = U''[x] + U'[x] + U[x];

Format[u[n_]] := Row[{u, n}]

expr2 = expr /. {Derivative[n_][U][_] :> u[n], U[_] :> u[0]}

enter image description here

Or,

Format[u[n_]] := Subscript[u, n]

expr2

enter image description here

Reversing the replacements

expr2 /. u[n_] :> Derivative[n][U][x]

enter image description here

$\endgroup$
1
  • $\begingroup$ Whoops, sorry I have no idea why I did not accept this nearly a year ago, but this was the perfect solution to my problem. $\endgroup$
    – akozi
    Sep 13 at 14:03

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.