/** * @param NumArray $matrix * @param NumArray $vector * @return NumArray */ protected static function backSubstitution(NumArray $matrix, NumArray $vector) { $shape = $matrix->getShape(); $xVector = \NumPHP\Core\NumPHP::zeros($shape[0]); for ($i = $shape[0] - 1; $i >= 0; $i--) { $sum = 0; for ($j = $i + 1; $j < $shape[0]; $j++) { $sum += $matrix->get($i, $j)->dot($xVector->get($j))->getData(); } $xVector->set($i, ($vector->get($i)->getData() - $sum) / $matrix->get($i, $i)->getData()); } return $xVector; }
/** * Tests NumArray::get with argument 0 on vector with size 1 */ public function testGet1Args0() { $numArray = new NumArray([1]); $expectedNumArray = new NumArray(1); $this->assertNumArrayEquals($expectedNumArray, $numArray->get(0)); }
/** * Searches the pivot index in an array * * @param NumArray $numArray given array * @param int $iIndex index * * @return int * * @since 1.0.0 */ protected static function getPivotIndex(NumArray $numArray, $iIndex) { $shape = $numArray->getShape(); $mAxis = $shape[0]; $max = abs($numArray->get($iIndex, $iIndex)->getData()); $maxIndex = $iIndex; for ($j = $iIndex + 1; $j < $mAxis; $j++) { $abs = abs($numArray->get($j, $iIndex)->getData()); if ($abs > $max) { $max = $abs; $maxIndex = $j; } } return $maxIndex; }
/** * 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; }