5
$\begingroup$

I am often facing the situation where I have a list $\{...x_k...\}$ and where I want to compute:

$$ \{...f[x_i,x_j]...\}\text{ with }\ i<j $$

Unfortunately, I have not been able to find an elegant solution for this problem. What I'm doing right now seems horrible to me (indirections etc...):

n = 4;
x = Table[RandomReal[], n]

{0.547984, 0.601967, 0.000917483, 0.738287}

Map[f[Apply[Sequence, x[[#]]]] &, 
    Flatten[Table[{i, j}, {i, 1, n}, {j, i + 1, n}], 1]]

{f[0.547984, 0.601967], f[0.547984, 0.000917483], f[0.547984, 0.738287], f[0.601967, 0.000917483], f[0.601967, 0.738287], f[0.000917483, 0.738287]}

(in real situation f is defined f[xi_,xj_]:= xi-xj for instance)

Question: what is a better (builtin?) solution?

$\endgroup$
0

1 Answer 1

7
$\begingroup$
Subsets[f @@ x, {2}]

{f[0.817389, 0.11142], f[0.817389, 0.789526], f[0.817389, 0.187803], f[0.11142, 0.789526], f[0.11142, 0.187803], f[0.789526, 0.187803]}

You can also use

f @@@ Subsets[x, {2}]
Join @@ Table[f @@ x[[{i, j}]], {i, 1, n}, {j, i + 1, n}]
$\endgroup$
0

Your Answer

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

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