/** * @return Matrix * * @throws MatrixException */ public function inverse() { if (!$this->isSquare()) { throw MatrixException::notSquareMatrix(); } $newMatrix = array(); for ($i = 0; $i < $this->rows; ++$i) { for ($j = 0; $j < $this->columns; ++$j) { $minor = $this->crossOut($i, $j)->getDeterminant(); $newMatrix[$i][$j] = fmod((double) ($i + $j), 2.0) == 0 ? $minor : -$minor; } } $cofactorMatrix = new self($newMatrix, false); return $cofactorMatrix->transpose()->divideByScalar($this->getDeterminant()); }