# Converting indices to expression and back

lets say I want to convert this

Subscript[PSternMat, 2, 13]


into this

PSternMat$2$13


I have written this rule

Subscript[PSternMat, 2, 13] /. {Subscript[n_, a_, b_] :>
ToExpression[ToString[n] <> "$" <> ToString[a] <> "$" <> ToString[b]]}


which works fine.

But now I want to convert it back into it's original form. How can I do that

Thanks!

• a quick solution might be something like Apply[Subscript, Through[{First, Sequence @@ Rest[#] &}[ Map[ToExpression, StringSplit[ToString[HoldForm[yourvar$123$12]], "$"]]]]] but I don't know how robust it might be generally speaking – user42582 Nov 1 '17 at 14:56 • This seems like more trouble than it's worth, just because you want to use subscripts. – J. M.'s ennui Nov 2 '17 at 6:03 ## 1 Answer c = PSternMat$2$13 Subscript@@ToExpression@StringSplit[ToString@c, "$"]

• I don't think your answer does what the OP asks.. The 1st argument to the Subscript form should be a symbol, and the remaining two should be integers. – m_goldberg Nov 2 '17 at 4:25
• i didn't think about it, i checked the result and the structure with TreeForm and they were equal, i didn't use SameQ, but now i think i fixed the error – Alucard Nov 2 '17 at 5:08
• This does work, but only in this specific case. If for instance the variable is squared and I want to convert it gives the wrong answer. – OhmSweetOhm Nov 2 '17 at 15:54
• Can pattern matching be used for the task? – OhmSweetOhm Nov 2 '17 at 15:54
• Maybe something using this: StringCases[ToString[PSternMat$2$13], n__ ~~ "$" ~~ a__ ~~ "$" ~~ b__] – OhmSweetOhm Nov 2 '17 at 15:59