123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 |
- <?php
- class CholeskyDecomposition
- {
-
- private $L = array();
-
- private $m;
-
- private $isspd = true;
-
- public function __construct($A = null)
- {
- if ($A instanceof Matrix) {
- $this->L = $A->getArray();
- $this->m = $A->getRowDimension();
- for ($i = 0; $i < $this->m; ++$i) {
- for ($j = $i; $j < $this->m; ++$j) {
- for ($sum = $this->L[$i][$j], $k = $i - 1; $k >= 0; --$k) {
- $sum -= $this->L[$i][$k] * $this->L[$j][$k];
- }
- if ($i == $j) {
- if ($sum >= 0) {
- $this->L[$i][$i] = sqrt($sum);
- } else {
- $this->isspd = false;
- }
- } else {
- if ($this->L[$i][$i] != 0) {
- $this->L[$j][$i] = $sum / $this->L[$i][$i];
- }
- }
- }
- for ($k = $i+1; $k < $this->m; ++$k) {
- $this->L[$i][$k] = 0.0;
- }
- }
- } else {
- throw new PHPExcel_Calculation_Exception(JAMAError(ARGUMENT_TYPE_EXCEPTION));
- }
- }
-
- public function isSPD()
- {
- return $this->isspd;
- }
-
- public function getL()
- {
- return new Matrix($this->L);
- }
-
- public function solve($B = null)
- {
- if ($B instanceof Matrix) {
- if ($B->getRowDimension() == $this->m) {
- if ($this->isspd) {
- $X = $B->getArrayCopy();
- $nx = $B->getColumnDimension();
- for ($k = 0; $k < $this->m; ++$k) {
- for ($i = $k + 1; $i < $this->m; ++$i) {
- for ($j = 0; $j < $nx; ++$j) {
- $X[$i][$j] -= $X[$k][$j] * $this->L[$i][$k];
- }
- }
- for ($j = 0; $j < $nx; ++$j) {
- $X[$k][$j] /= $this->L[$k][$k];
- }
- }
- for ($k = $this->m - 1; $k >= 0; --$k) {
- for ($j = 0; $j < $nx; ++$j) {
- $X[$k][$j] /= $this->L[$k][$k];
- }
- for ($i = 0; $i < $k; ++$i) {
- for ($j = 0; $j < $nx; ++$j) {
- $X[$i][$j] -= $X[$k][$j] * $this->L[$k][$i];
- }
- }
- }
- return new Matrix($X, $this->m, $nx);
- } else {
- throw new PHPExcel_Calculation_Exception(JAMAError(MatrixSPDException));
- }
- } else {
- throw new PHPExcel_Calculation_Exception(JAMAError(MATRIX_DIMENSION_EXCEPTION));
- }
- } else {
- throw new PHPExcel_Calculation_Exception(JAMAError(ARGUMENT_TYPE_EXCEPTION));
- }
- }
- }
|