Unexpected Behavior in Sum[a + Subscript[a, 1], {a, 1, 2}]

The simple command

Sum[a + Subscript[a, 1], {a, 1, 2}]

gives the unexpected result

4 + Subscript[2, 1]

while what I want is $$3+2a_1$$.

I think the problem is due to the unwanted subsitution of $$a_1$$ while summing over $$a$$. How can I resolve this problem, by not changing the variable name? (The actual expression that I want to evaluate is much more complicated.)

• Which version are you on? Is this with a fresh kernel without definitions of a? Sep 17 '21 at 10:26
• @SHuisman I am in 12.1 and the kernel is fresh without any definition of a. Sep 17 '21 at 10:30
• Use Subscript[HoldForm[a],1]. The result you get is not unexpected. Sep 17 '21 at 10:31
• also Sum[a + Subscript[Defer@a, 1], {a, 1, 2}] and Sum[a + Defer@Subscript[a, 1], {a, 1, 2}]
– kglr
Sep 17 '21 at 10:37
• I mean, why not do Sum[x + Subscript[a, 1], {x, 1, 2}]? Sep 17 '21 at 18:48

To avoid the problem where structural elements (e.g., Subscript) that contain the solve variable prevent functions like Sum, Solve, etc. from working, you can do the following:

Unprotect[Sum];
Sum[e__] /; !FreeQ[Hold[e], _Subscript] := Block[{CompressedData},
With[{res = Sum @@ ReplaceAll[{e}, s_Subscript :> CompressedData[Compress@s]]},
res /; !MatchQ[res, _Sum]
]
]
Protect[Sum];

The above code temporarily converts the subscript to a string, then performs the sum, then restores the subscript. For your example:

Sum[a + Subscript[a, 1], {a, 1, 2}]

3 + 2 Subscript[a, 1]

The HoldForm[] command shall "hold" the "form" of the argument it takes, without substituting that argument with the value you might have assigned to the argument variable elsewhere.

Sum[a + Subscript[HoldForm[a], 1], {a, 1, 2}]

gives the result you wish to get.

If you wish to get rid of the HoldForm action on a variable later on, use ReleaseHold.