2
$\begingroup$

I have an expression of the form:

expression = A1*x + A2*x^2 + ...

and I would like to replace A1 by F1[y], A2 by F2[y], etc.

Regular expressions would seem to be the thing to use, but since the above is not a string, I'm not sure how to do this. Would like the solution to be something simple like

expression /. A* :> F*[y]

but of course this doesn't work.

How do I accomplish the above?

$\endgroup$
  • 3
    $\begingroup$ How are you generating your expression? It might be easier to replace A1,A2,… by A[1],A[2],…. Then, replacement becomes as simple as expression /. A[i_] :> F[i][y]. As a general rule i try to keep any information that I might need again out of symbol names - most function have no issue with composite heads, and it makes extracting the information so much easier $\endgroup$ – Lukas Lang Jan 13 at 18:00
  • $\begingroup$ Yeah that's the problem, the output is from a function in the xAct xTras package and it spits out expressions of the above form with Ai's, rather than A[i]'s. Doesn't seem to be a way of changing it. (MakeContractionAnsatz) $\endgroup$ – user26866 Jan 14 at 18:37
9
$\begingroup$

You can use SymbolName to convert symbols to their string names, and then process those strings:

ReplaceAll[
    A1*x + A2*x^2 + A3*x^3,
    s_Symbol :> Module[{n = SymbolName[s]},
        Symbol[StringReplace[n, "A"->"F"]][y] /; StringMatchQ[n, "A"~~DigitCharacter..]
    ]
]

x F1[y] + x^2 F2[y] + x^3 F3[y]

$\endgroup$
  • $\begingroup$ Beautiful, thanks! $\endgroup$ – user26866 Jan 13 at 19:39
5
$\begingroup$

Here is an approach based on string manipulation:

expression = A1 x + A2 x^2 + A3 x^3;

ToString@InputForm@expression;
StringReplace[%, "A" ~~ n : DigitCharacter :> "F" ~~ n ~~ "[y]"];
ToExpression@%

(* x F1[y] + x^2 F2[y] + x^3 F3[y] *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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