Let's assume the following test data
k = 3;
vars = Array[i, k];
imax = RandomInteger[{1, 5}, k];
(*
vars is {i[1], i[2], i[3]}
imax is here {3, 5, 4}
*)
then the nested sum you try to achieve can be written as
Sum[f @@ vars, Evaluate[Sequence @@ ({#1, 0, #2} & @@@ Transpose[{vars, imax}])]]
Since I used a lot of operators which may not be easy to use by new Mathematica users, let me explain the approach in detail. What I want to create first is a list of your iterators. For this I first use Transpose[{vars, imax}]
to create list which has the iteration variable and its upper bound side by side:
Transpose[{vars,imax}]
(* Out[5]= {{i[1],1},{i[2],3},{i[3],2}} *)
Now I need to transform this into the form {i[n],0,imaxn}
. Therefore I use an anonymous function {#1, 0, #2}&
. This function needs to be called like {#1, 0, #2}&[i[1],1]
to work but we have sublist elements. They are in the form List[i[1],1]
. If I would replace the List
head with the anonymous function, everything would be fine. This is the reason why @@@
is used which replaces the heads of the elements inside the main list.
{#1,0,#2}&@@@Transpose[{vars,imax}]
(* Out[6]= {{i[1],0,1},{i[2],0,3},{i[3],0,2}} *)
In the above step we get a list of iteration bounds. This is not useful because we need to give them as Sequence
to Sum
. Therefore, we again replace a head but this time we replace the List
head of the main iterator list by Sequence
. Therefore @@
is used in contrast to @@@
which we used to replaced the heads of the elements of the list.
This very same trick is used to apply f
to all iteration variables. We have them in a list vars
and writing f@@vars
creates f[i[1],i[2],...,i[k]]
.
In a last step we have to remember, that Sum
has the attribute HoldAll
. Therefore, it does not evaluate our iterator bounds we created so nicely. Instead it sees the whole expression
Sequence @@ ({#1, 0, #2} & @@@ Transpose[{vars, imax}])
which would lead to an error message because Sum
expects appropriate bounds. The required evaluation of the above, before Sum
sees it can be forced by Evaluate
.
Sum[f,{i,imin,imax},{j,jmin,jmax}]
? Maybe you can take a look at this and this. $\endgroup${i,imin,imax,di}
,wheredi
is the step size. $\endgroup$Total[Array[f[#1, #2, ...] &, {imax1, imax2, ...}, {0, 0, ...}], -1]
. $\endgroup$