You are here

static function Matrix::correlation in Recommender API 7.6

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

Compute the covariance matrix for the row vectors.

Parameters

$matrix Could be RealMatrix or SparseMatrix.:

Return value

Matrix a new m by m covariance matrix. don't have to return by ref, because the engine will take care of it. Note that no matter what's the input matrix, the returned matrix is always a sparse matrix.

1 call to Matrix::correlation()
CFRecommender::computeSimilarity in classes/Recommender.php

File

classes/Matrix.php, line 87

Class

Matrix
This PHP file does not require Drupal. Including both Matrix and Vector implementation. Missing data are treated as NAN. Some extra complexity comes from trying to increase memory/cpu performance Note, this implementation does check input parameters.…

Code

static function correlation($matrix) {
  $vectors = $matrix
    ->row_vectors();
  $m = $matrix->row;

  // dimension of the correlation matrix
  $cor_matrix = Matrix::create('SparseMatrix', $m, $m);
  for ($v1 = 0; $v1 < $m; $v1++) {
    for ($v2 = $v1; $v2 < $m; $v2++) {
      if (isset($vectors[$v1]) && isset($vectors[$v2])) {

        // note, some value (such as std) is cached, so it won't be too much performance problem.
        $cor = $vectors[$v1]
          ->correlation($vectors[$v2]);
        if (!is_nan($cor)) {
          $cor_matrix
            ->set($v1, $v2, $cor);
          $cor_matrix
            ->set($v2, $v1, $cor);
        }
      }
    }
  }
  return $cor_matrix;
}