Returns a NumArray with the same size, but filled with 0
public static zerosLike ( |
||
$numArray | given NumArray | |
Résultat |
/** * Calculates lower triangular matrix L of given symmetric positive definite matrix * * @param NumArray $squareMatrix symmetric positive definite matrix * * @return NumArray * * @throws InvalidArgumentException will be thrown, when `$squareMatrix` is not positive definite * @throws NoSquareMatrixException will be thrown, when `$squareMatrix` is not square * @throws NoSymmetricMatrixException will be thrown, when `$squareMatrix` is not symmetric * * @since 1.0.2 */ public static function cholesky(NumArray $squareMatrix) { if (!Helper::isSquareMatrix($squareMatrix)) { throw new NoSquareMatrixException(sprintf("Matrix with shape (%s) given, matrix has to be square", implode(', ', $squareMatrix->getShape()))); } $shape = $squareMatrix->getShape(); $size = $shape[0]; $aMatrix = clone $squareMatrix; $lMatrix = NumPHP::zerosLike($aMatrix); for ($k = 0; $k < $size; $k++) { $diaElem = $aMatrix->get($k, $k)->getData(); if ($diaElem <= 0) { throw new InvalidArgumentException("Matrix is not positive definite"); } $diaElem = sqrt($diaElem); $lMatrix->set($k, $k, $diaElem); for ($i = $k + 1; $i < $size; $i++) { if ($squareMatrix->get($i, $k) != $squareMatrix->get($k, $i)) { throw new NoSymmetricMatrixException("Matrix is not symmetric"); } $lMatrix->set($i, $k, $aMatrix->get($i, $k)->div($diaElem)); for ($j = $k + 1; $j <= $i; $j++) { $aMatrix->set($i, $j, $aMatrix->get($i, $j)->sub($lMatrix->get($i, $k)->mult($lMatrix->get($j, $k)))); } } } return $lMatrix; }
/** * Tests NumPHP::zerosLike with 2x3 matrix */ public function testZerosLike() { $numArray = new NumArray([[1, 2, 3], [4, 5, 6]]); $expectedNumArray = NumPHP::zeros(2, 3); $this->assertNumArrayEquals($expectedNumArray, NumPHP::zerosLike($numArray)); }
/** * Back Substitution solves a linear system with a upper triangular matrix of * size n*n and a vector of size n or a matrix of size n*m * * @param NumArray $uMatrix upper triangular matrix of size n*n * @param NumArray $numArray vector of size n or matrix of size n*m * * @return NumArray * * @since 1.0.0 */ protected static function backSubstitution(NumArray $uMatrix, NumArray $numArray) { $shape = $numArray->getShape(); if (Helper::isVector($numArray)) { $xVector = NumPHP::zerosLike($numArray); for ($i = $shape[0] - 1; $i >= 0; $i--) { $slice = sprintf("%d:%d", $i + 1, $shape[0]); $sum = $uMatrix->get($i, $slice)->dot($xVector->get($slice)); $xVector->set($i, $numArray->get($i)->sub($sum)->div($uMatrix->get($i, $i))); } return $xVector; } // $numArray is a matrix $copy = clone $numArray; for ($i = 0; $i < $shape[1]; $i++) { $copy->set(':', $i, self::backSubstitution($uMatrix, $copy->get(':', $i))); } return $copy; }