I have a list of the form {a x[1] + x[2, 3], w A[3, 4] + x[1]}, where I want to replace all the indices as subscripts, ie, the output should be of the form: {a Subscript[x, 1] + Subscript[x, 2, 3], w Subscript[A, 3, 4] + Subscript[x, 1]}. I tried to use the pattern matching {a x[1] + x[2, 3], w A[3, 4] + x[1]} /. {a_[b_] -> Subscript[a, b]} which converts the single index entries, but it does not apply to double indices entries. If I try {a x[1] + x[2, 3], w A[3, 4] + x[1]} /. {a_[b_] -> Subscript[a, b], x_[y_, z_] -> Subscript[x, y, z]} I get Subscript[List, a*x[1] + x[2, 3], w*A[3, 4] + x[1]]. How to convert both single and double indices as subscripts?
3 Answers
Instead of using Blank (_), use BlankSequence (__). But as @SHuisman warns, you also have to be careful not to apply this rule to unwanted (system) functions. Instead of manually providing a list of exception, you can check the Context of a symbol.
expr = {a x[1] + x[2, 3], w A[3, 5] + x[1]}; rule = a_[b__] :> Subscript[a, b] /; Context[a] =!= "System`" expr /. rule (* {a*Subscript[x, 1] + Subscript[x, 2, 3], Subscript[x, 1]^2 + w*Subscript[A, 3, 5]} *) $Version (* "14.1.0 for Mac OS X ARM (64-bit) (July 16, 2024)" *) expr = {a x[1] + x[2, 3], w A[3, 4] + x[1]}; Replacement is not necessary. Just Format the indexed variables to display as Subscript
(Format[#[n__]] := Subscript[#, Row[{n}]]) & /@ {A, x}; expr Or, with commas
(Format[#[n__]] := Subscript[#, n]) & /@ {A, x}; expr - 1$\begingroup$ That is such a neat solution, thanks so much! $\endgroup$TDH– TDH2025-01-16 23:09:01 +00:00Commented Jan 16 at 23:09
Since the pattern you supplied is so general it will match Plus, Times, List etc, so you have to limit the pattern a bit:
rules = {a_[b_]:>Subscript[a,b],(x:Except[Times|List|Plus,_])[y_,z_]:>Subscript[x,y,z]} {a x[1]+x[2,3],w A[3,4]+x[1]} /. rules 

Subscript. It is almost always the wrong solution. Better useIndexed[x,1],Indexed[A,{3,4}]etc. $\endgroup$