/** * Cholesky algorithm for symmetric and positive definite matrix. * * @param * matrix * Square, symmetric matrix. */ public function __construct(Matrix $matrix) { // Initialize. $a = $matrix->getData(); $this->n = $matrix->getRows(); $this->l = new \ArrayObject(); for ($r = 0; $r < $this->n; ++$r) { $this->l[$r] = new \ArrayObject(); for ($c = 0; $c < $this->n; ++$c) { $this->l[$r][$c] = 0.0; } } $this->isspd = $matrix->getCols() == $this->n; // Main loop. for ($j = 0; $j < $this->n; ++$j) { $lrowj = $this->l[$j]; $d = 0.0; for ($k = 0; $k < $j; ++$k) { $lrowk = $this->l[$k]; $s = 0.0; for ($i = 0; $i < $k; ++$i) { $s += $lrowk[$i] * $lrowj[$i]; } $s = ($a[$j][$k] - $s) / $this->l[$k][$k]; $lrowj[$k] = $s; $d = $d + $s * $s; $this->isspd = $this->isspd & $a[$k][$j] == $a[$j][$k]; } $d = $a[$j][$j] - $d; $this->isspd = $this->isspd & $d > 0.0; $this->l[$j][$j] = sqrt(max($d, 0.0)); for ($k = $j + 1; $k < $this->n; ++$k) { $this->l[$j][$k] = 0.0; } } }
/** * Randomize the matrix based on an array, modify the array. * Previous values * may be used, or they may be discarded, depending on the randomizer. * * @param * Matrix m * A matrix to randomize. */ public function randomizeMatrix(Matrix &$m) { $d = $m->getData(); for ($r = 0; $r < $m->getRows(); ++$r) { for ($c = 0; $c < $m->getCols(); ++$c) { $d[$r][$c] = $this->randomizeDouble($d[$r][$c]); } } $m->setData($d); }
/** * Return the transposition of a matrix. * * @param $input Matrix * The matrix to transpose. * @return Matrix The matrix transposed. */ function transpose(Matrix $input) { $transposeMatrix = array(); $d = $input->getData(); for ($r = 0; $r < $input->getRows(); ++$r) { for ($c = 0; $c < $input->getCols(); ++$c) { $transposeMatrix[$c][$r] = $d[$r][$c]; } } return Matrix::matrixFromDoubles($transposeMatrix); }