# How to find all possible correlations between n vectors

Given the Matrix

M = {{31.3, 31.2, 29.7, 29.7, 29.8, 29.2, 28.7, 28.3, 28.2, 28.2},
{31.7, 30.7, 30.7, 30.1, 30.2, 29.8, 29.2, 28.7, 28.5, 27.7},
{24.0, 24.2, 23.7, 23.7, 23.2, 23.1, 22.6, 22.2, 22.1, 21.7},
{23.2, 22.2, 22.2, 22.0, 22.2, 21.8, 19.5, 19.1, 19.1, 18.9}};


I want to get a list of all possible correlations between its vectors.

With

x1 = Take[#, 2] & /@ Permutations[Range@Length@M];


And

x2 = Union@Cases[x1, {a_, b_} /; a < b];


I get the necessary permutation:

{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}


Finally, with

Correlation @@@ Partition[M[[Flatten@x2]], 2]


I get the desired result:

{0.923, 0.933, 0.893, 0.952, 0.946, 0.934}


I am, of course, not happy with this code and would wellcome any suggestion how one could write this succinctly.

• Are you looking for Subsets[..., {2}]? Commented May 30, 2014 at 16:07
• @Szabolcs - Thanks, "Cases[Subsets[Range@Length@M, 2], {_, _}]" is very nice ! But I also think that the following "Partition[M[[Flatten@x2]], 2]" is not the most efficient way.
– eldo
Commented May 30, 2014 at 16:17
• Correlation @@@ Subsets[M, {2}]?
– kglr
Commented May 30, 2014 at 19:31
• @kguler - you make me speechles. Why didn't you post this as the one and only answer? You don't want me to earn two pennies by accepting it?
– eldo
Commented May 30, 2014 at 19:47
• @eldo, you got your two 'pennies' :)
– kglr
Commented May 30, 2014 at 19:56

Correlation @@@ Subsets[M, {2}]