You are here

function Vector::covariance in Recommender API 7.6

Same name and namespace in other branches
  1. 6.2 Matrix.php \Vector::covariance()

Compute covariance with $vector. No caching option. Works for RealVector. SparseVector needs additional handling.

Parameters

$vector it has to be the same type (either SparseVector or RealVector) as $this:

Return value

covariance value

1 call to Vector::covariance()
Vector::correlation in classes/Matrix.php
Compute correlation with $vector. No caching option. Works for RealVector. SparseVector needs additional handling.
1 method overrides Vector::covariance()
SparseVector::covariance in classes/Matrix.php
Compute covariance with $vector. No caching option. Works for RealVector. SparseVector needs additional handling.

File

classes/Matrix.php, line 245

Class

Vector
This is the Vector superclass. @author danithaca

Code

function covariance(&$vector) {

  // $arary_a and $array_b just pass by reference
  $array_a =& $this->values;
  $array_b =& $vector->values;
  $mean_a = $this
    ->mean(TRUE);
  $mean_b = $vector
    ->mean(TRUE);
  $count = $this
    ->count(TRUE);

  // if the vector doesn't have any elements, covariance would be NAN.
  if ($count == 0) {
    return NAN;
  }
  $covariance = 0;
  for ($i = 0; $i < $count; $i++) {
    $covariance += ($array_a[$i] - $mean_a) * ($array_b[$i] - $mean_b);
  }
  return $covariance / $count;
}