0

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[1]
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[[1]], sb[[1]], se[[1]]}, 
 Evaluate@{vars[[2]], sb[[2]], se[[2]]}, 
 Evaluate@{vars[[3]], sb[[3]], se[[3]]}]

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[[1]], sb[[1]], se[[1]]}, 
 Evaluate@{vars[[2]], sb[[2]], se[[2]]}, 
 Evaluate@{vars[[3]], sb[[3]], se[[3]]}]

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?

egwene sedai
  • 2,355
  • 16
  • 24

1 Answers1

4

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[1], s1tart, s1end}, {s[2], s2start, s2end}}

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

NonDairyNeutrino
  • 7,810
  • 1
  • 14
  • 29