1
$\begingroup$

In Mathematica, I am doing computations involving polynomials with variables like

p[0,1,2]

In the end, I will need to put these equations in to another program. This other program does not allow brackets or commas in variable names. So, I need to send the above variable to

p012

Ultimately, I need my entire list of polynomials to be in input form which I can copy and paste into the other program. I have tried writing something like

StringVar[i_, j_, k_] := StringForm["p``````", i, j, k]

And then using Simplify to substitute the variables. But, when I use InputForm on the entire list of polynomials I get these funny expressions

StringForm["p``````", 0, 1, 2]

instead of the variables p012 that I would like. How do I make Mathematica treat these as variables?

$\endgroup$
3
$\begingroup$

I think the simplest approach is to give p a Format:

Format[p[a__Integer], InputForm] := SequenceForm[p,a]

Here is an example polynomial, and what it looks like when converted to InputForm:

poly = 2 p[0,1,2]^2 + p[1,2,3]^3
% //InputForm

enter image description here

$\endgroup$
1
$\begingroup$

This is a common trap with using StringForm[]. But before discussing the pitfall, let me offer slightly simpler code:

With[{expr = p[0, 1, 2]},
     StringForm["`1``2`", Head[expr], StringJoin[ToString /@ (List @@ expr)]]]
   p012

Looks good so far, but let's see what InputForm[] says:

InputForm[%]
   StringForm["`1``2`", p, "012"]

Certainly not a string!

So, you need an additional ToString[]:

ToString[%] // InputForm
   "p012"

The alternative in newer versions of Mathematica is StringTemplate[], which produces a genuine string. Observe:

With[{expr = p[0, 1, 2]},
     StringTemplate["`head``args`"] @
     <|"head" -> Head[expr], "args" -> StringJoin[ToString /@ (List @@ expr)]|>]
   "p012"
$\endgroup$
  • $\begingroup$ ...and you can then use Symbol["p012"] much later if you really want symbols instead of strings. $\endgroup$ – J. M. will be back soon Oct 3 '17 at 1:29
0
$\begingroup$

If I understand what you're trying to do, this is the replacement rule you're looking for:

rule = p[i_, j_, k_] :> ToExpression[StringJoin @@ (ToString /@ {"p", i, j, k})]

You might also consider using Format and/or $PrePrint to have the expressions automatically formatted.

$\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.