Skip to content

Instantly share code, notes, and snippets.

@guyb7
Created August 27, 2014 17:37
Show Gist options
  • Select an option

  • Save guyb7/7ff4436bf5b3b62eaaa1 to your computer and use it in GitHub Desktop.

Select an option

Save guyb7/7ff4436bf5b3b62eaaa1 to your computer and use it in GitHub Desktop.
PHP implementation of Pearson's product-moment correlation coefficient
<?php
// PHP implementation of Pearson's product-moment correlation coefficient
function corr($a, $b) {
$sum_ab = 0;
$sum_a = 0;
$sum_b = 0;
$sum_a_sqr = 0;
$sum_b_sqr = 0;
$n = min(array(count($a), count($b)));
for ($i = 0; $i < $n; $i++) {
if (!isset($a[$i]) || !isset($b[$i])) { continue; }
$sum_ab += $a[$i] * $b[$i];
$sum_a += $a[$i];
$sum_b += $b[$i];
$sum_a_sqr += pow($a[$i], 2);
$sum_b_sqr += pow($b[$i], 2);
}
return ($sum_ab/$n - $sum_a/$n * $sum_b/$n) / (sqrt($sum_a_sqr/$n - pow($sum_a/$n, 2)) * sqrt($sum_b_sqr/$n - pow($sum_b/$n, 2)));
}
$a1 = array(0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0);
$b1 = array(1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1);
echo corr($a1, $b1) . "\n<br/>";
$a2 = array(1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1);
$b2 = array(1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0);
echo corr($a2, $b2) . "\n<br/>";
$a3 = array(1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0);
$b3 = array(1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0);
echo corr($a3, $b3) . "\n<br/>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment