3
$\begingroup$

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.

$\endgroup$
5
  • $\begingroup$ Are you looking for Subsets[..., {2}]? $\endgroup$
    – Szabolcs
    Commented May 30, 2014 at 16:07
  • $\begingroup$ @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. $\endgroup$
    – eldo
    Commented May 30, 2014 at 16:17
  • $\begingroup$ Correlation @@@ Subsets[M, {2}]? $\endgroup$
    – kglr
    Commented May 30, 2014 at 19:31
  • $\begingroup$ @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? $\endgroup$
    – eldo
    Commented May 30, 2014 at 19:47
  • $\begingroup$ @eldo, you got your two 'pennies' :) $\endgroup$
    – kglr
    Commented May 30, 2014 at 19:56

1 Answer 1

7
$\begingroup$
Correlation @@@ Subsets[M, {2}]
(* {0.923, 0.933, 0.893, 0.952, 0.946, 0.934}  *)
$\endgroup$

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.