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());
}
public function testInverseMatrix() { //http://ncalculators.com/matrix/inverse-matrix.htm $matrix = new Matrix([[3, 4, 2], [4, 5, 5], [1, 1, 1]]); $inverseMatrix = [[0, -1, 5], [1 / 2, 1 / 2, -7 / 2], [-1 / 2, 1 / 2, -1 / 2]]; $this->assertEquals($inverseMatrix, $matrix->inverse()->toArray(), '', $delta = 0.0001); }