public function inverse() : Matrix
{
if (isset($this->A⁻¹)) {
return $this->A⁻¹;
}
if (!$this->isSquare()) {
throw new Exception\MatrixException('Not a sqaure matrix (required for determinant)');
}
$│A│ = $this->det ?? $this->det();
if ($│A│ == 0) {
throw new Exception\MatrixException('Singular matrix (determinant = 0); not invertible');
}
$m = $this->m;
$n = $this->n;
$A = $this->A;
/*
* 2x2 matrix:
* [a b]
* A = [c d]
*
* 1
* A⁻¹ = --- [d -b]
* │A│ [-c a]
*/
if ($m === 2) {
$a = $A[0][0];
$b = $A[0][1];
$c = $A[1][0];
$d = $A[1][1];
$R = MatrixFactory::create([[$d, -$b], [-$c, $a]]);
$A⁻¹ = $R->scalarMultiply(1 / $│A│);
$this->A⁻¹ = $A⁻¹;
return $A⁻¹;
}
/*
* nxn matrix 3x3 or larger
*/
$R = $this->augmentIdentity()->rref();
$A⁻¹ = [];
for ($i = 0; $i < $n; $i++) {
$A⁻¹[$i] = array_slice($R[$i], $n);
}
$A⁻¹ = MatrixFactory::create($A⁻¹);
$this->A⁻¹ = $A⁻¹;
return $A⁻¹;
}