1
$\begingroup$

Is there neat way to implement following sums in mathematica? $$s(l,k)=\sum\limits_{p_1+p_2+...+p_l=k} f_l(p_1,p_2,...,p_l) $$ and $$t(l)=\sum\limits_{i_1,i_2,...,i_l=1}^n f_l(i_1,i_2,...,i_l)$$ Where $p_1,...,p_l\geq1$ ($p_1,...p_l\in\mathbb N$) and $l\in\mathbb N$ isn't fixed?

It seems I could use IntegerPartitions{k,{l}}, but this doesn't really seem neat! I'm also having trouble with implementing the 2nd sum, as $l$ is variable.

$\endgroup$
  • $\begingroup$ I think I can get it running with IntegerPartitions. Still I want to ask how to implement $t(l)$ in a nice way? $\endgroup$ – user40804 Jun 6 '16 at 12:49
  • $\begingroup$ FrobeniusSolve[] may be more expedient than IntegerPartitions[] in your first sum, if only a little slower. For your second: Sum[f @@ Array[K, l], ##] & @@ Transpose[PadRight[{Array[K, l]}, {2, Automatic}, n]] is an obvious solution, but there might be more efficient ones, more so if your $f_l$ has symmetry of some sort. $\endgroup$ – J. M. will be back soon Jun 6 '16 at 13:52
  • $\begingroup$ Ok, I'll stick with IntegerPartitions for now, but I guess I can use FrobeniusSolve for more general sums! Thanks for the comment anyways! $\endgroup$ – user40804 Jun 6 '16 at 14:02
2
$\begingroup$

Three ways of computing t[l]:

Using Sum:

Sum[ f @@ Table[i[j], {j, l}], ##] & @@ Table[{i[j], n}, {j, l}]

Generating all index lists:

Total[f @@@ Tuples[Range[n], l]]

Recursive:

rec[depth_] := If[depth == 0, f @@ Table[i[j], {j, l}], Sum[rec[depth - 1], {i[depth], n} ] ];
rec[l]
$\endgroup$
  • $\begingroup$ Thanks alot! I didn't know "Tuples"! I really like this one! Looks very clean to me! I think I'll use the second one, so I can setup my f[] very easy, so the argument can be a tuple! $\endgroup$ – user40804 Jun 6 '16 at 13:59
  • $\begingroup$ Hey, I've got another question: I have multiple lists (t1,t2,t3,t4) and i want to make a new list such that it contains all elements of the form {a,b,c,d} where a,b,c,d are from t1,t2,t3,t4. I figured out I could use Flatten[Table[{t1[[i]], t2[[j]]}, {i, Length[t1]}, {j, Length[t2]}], 1] (here for 2 lists) but this doesn't seem very satisfiying! Is there a better way? $\endgroup$ – user40804 Jun 6 '16 at 15:19
  • $\begingroup$ Use Tuples again! See the docs. $\endgroup$ – Marius Ladegård Meyer Jun 6 '16 at 16:06
  • $\begingroup$ Haha thanks again! I guess all I needed was Tuples!!! $\endgroup$ – user40804 Jun 6 '16 at 16:21

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.