0
$\begingroup$

I would like to write a function that generates the expression $\sum_{i_1,\ldots,i_L} f(i_1,\ldots,i_L) \left(s_{i_1}\ldots s_{i_L}\right)$

where $i_j\in \left\{0,1,2,3\right\}$ and $s_{i_j}$ are string variables. The parameter to be passed to the function is the number of terms $L$. For example for L=2 one could generate it with

Sum[f[{j, k}] ("s" <> ToString@j <> " " <> "s" <> ToString@k), {j, 0, 3}, {k, 0, 3}]

However I would like to create a function

g[L_]:=...

That generalise the previous expression for arbitrary L. Maybe this could be done by creating a list

variables={j1,... ,jL}

which could be passed to a function of variable number of arguments as

g[variables__]:=... 

? Is it a better way to do it?

$\endgroup$
2
  • $\begingroup$ According to your description, the sum above should be {j, 0, 3}, {k, 0, 3}, right? $\endgroup$
    – Jens
    Jul 20, 2017 at 16:17
  • $\begingroup$ yes you're right $\endgroup$
    – Galuoises
    Jul 21, 2017 at 8:46

1 Answer 1

2
$\begingroup$

There are many ways to do this kind of thing, but the least work is probably to use Array. For example, if we define

sumindices[func_,numindices_Integer]:=Plus@@Flatten@Array[func,Table[2,{numindices}],0]

Given a generic function g, if we type

sumindices[g, 2]

we then get

g[0, 0] + g[0, 1] + g[1, 0] + g[1, 1]

To get the output you want, we then define a function to make the string

makestr[indices___]:= StringDrop[StringJoin@@("s"<>ToString[#]<>" "&/@{indices}),-1]

Then we can define

makef[indices___]:= f[{indices}][makestr[indices]]

And your desired output should be

sumindices[makef,2]

which gives

f[{0, 0}]["s0 s0"] + f[{0, 1}]["s0 s1"] + f[{1, 0}]["s1 s0"] + f[{1, 1}]["s1 s1"]
$\endgroup$
1
  • $\begingroup$ it works perfectly. I modified Table[2,{numindices}] to Table[4,{numindices}] to let the indices go from 0 to 3 $\endgroup$
    – Galuoises
    Jul 21, 2017 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.