You are here

static function Matrix::correlation in Recommender API 6.2

Same name and namespace in other branches
  1. 7.6 classes/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.

2 calls to Matrix::correlation()
CorrelationRecommender::computeSimilarityMemory in ./Recommender.php
RecommenderMatrixTestCase::testMatrix in ./recommender.test

File

./Matrix.php, line 92

Class

Matrix
This PHP file has to work with 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;
}