2
$\begingroup$

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.)

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

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]

$\endgroup$
4
$\begingroup$

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.

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