5
$\begingroup$

As a minimal example, define a function like s[1,2,3]; this is a function of three arguments in this case, but I'd like to apply this general idea to functions like s[3,4,5,6,7] which don't necessarily start at 1.

From an identity from theory, I need to re-express this as as sum of 2-argument functions that cycle over all of the possible combinations of the original function, but don't duplicate. Explicitly, this would be the same as writing

s[1,2,3]=f[1,2]+f[1,3]+f[2,3],

or in the longer more general case (and to illustrate my point)

s[3,4,5,6,7] = f[3,4]+f[3,5]+f[3,6]+f[3,7]+f[4,5]+f[4,6]+f[4,7]+f[5,6]+f[5,7]+f[6,7]

I was previously using the definition with simple replacement rules for each of the these chains, with general cases of s[i_,j_,k_] and such similar rules. However, this isn't optimal in larger problems, where I have many thousands of these results, and leads to remarkably long evaluation times.

To see my functional but slow solution, I have attached a partial screenshot here, but naturally, I think there must be a better method. I was considering using Partitions, as in this SE post or BlankSpaces, but I struggle to implement more complex uses of these. Any guidance or other ideas would be gratefully appreciated. Also, a title suggestion would be great as well!

$\endgroup$
  • $\begingroup$ Look into Subsets[listOfArguments, {2}] $\endgroup$ – MarcoB Mar 2 at 19:00
7
$\begingroup$

Something like the following?

ClearAll[s]
s[seq__] := Total[f@@@Subsets[List[seq], {2}]]
$\endgroup$
  • $\begingroup$ Hi @MarcoB - Subsets was indeed the function I was looking for. I was thinking perhaps of more of a general replacement rule at the end, where in my final stage I remove all of the (previously defined) functions s, in exchange for these functions p. I will try and play around and see if I can figure out how to create a replacement rule based on this method. Thank you for your help: $\endgroup$ – Brad Mar 2 at 19:28
  • $\begingroup$ After changing my definition of recursion to work with a symbolic sX, which actually makes evaluations much much faster overall, I can utilise this to get exactly what I need. Thank you all for your help, this is the fastest solution I found. $\endgroup$ – Brad Mar 2 at 20:43
7
$\begingroup$
ClearAll[s]
s[f_] := Total @ Subsets[f @ ##, {2}] &;

s[f][a, b, c]

f[a, b] + f[a, c] + f[b, c]

s[f][3, 4, 5, 6, 7]

f[3, 4] + f[3, 5] + f[3, 6] + f[3, 7] + f[4, 5] + f[4, 6] + f[4, 7] + f[5, 6] + f[5, 7] + f[6, 7]

$\endgroup$

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.