# Programatically generating variables and sum

Given a set of variables, say s1through sn, and a way to generate an expression expr dependent on these variables, I then want to sum over all these variables,

Sum[expr, {s1,s1start,s1end},{s2,s2start,s2end}...]

where s1start/s1end... are stored in an array (numerical values). Question is, what is a good way to generate this set of variables and is there a way to programmatically code the Sum to go over all variables?

minimum working example: (in real code expr comes from more complex operations, not just linear vector/matrix multiplications)

nd = 3;

SeedRandom
a = RandomReal[{0, 1}, nd];

sb = Table[1, {i, 1, nd}]; (*summing index: begin*)
se = Table[10, {i, 1, nd}]; (*summing index: end *)

vars = Table[ToExpression["s" <> ToString[i]], {i, 1, nd}];
expr = a.vars;

Sum[expr, Evaluate@{vars[], sb[], se[]},
Evaluate@{vars[], sb[], se[]},
Evaluate@{vars[], sb[], se[]}]


I may also choose not to use the ToExpression and use some undefined function symbol as summing index/variables

Clear[m]
vars = Table[m[i], {i, 1, nd}];
expr = a.vars;
Sum[expr, Evaluate@{vars[], sb[], se[]},
Evaluate@{vars[], sb[], se[]},
Evaluate@{vars[], sb[], se[]}]


I can code the sum to go through the varibles like

si = Table[{vars[[i]], sb[[i]], se[[i]]}, {i, 1, nd}]
PrependTo[si, expr]
Sum @@ si


but both the ToExpression["x" <> ToString[i]] approach and the function symbol approach does not look 'clean' to me. Is there a preferred way to achieve this?

ps. The function symbol approach is similar to How to Sum with indefinite variables?, just wondering if such use is good practice/ are there better ways to do this?

## 1 Answer

Coming from this answer on "How to programmatically specify multiple iterators?"

endpoints = {{s1tart, s1end}, {s2start, s2end}};

Table[{s[k], Sequence @@ endpoints[[k]]}, {k, 2}]
(*or*) MapIndexed[Prepend[#1, s @@ #2] &, endpoints]

HoldForm@Sum[expr, ##] & @@ %

{{s, s1tart, s1end}, {s, s2start, s2end}}

HoldForm[Sum[expr, {s, s1tart, s1end}, {s, s2start, s2end}]]