mirror of
https://github.com/Llewellynvdm/php-ml.git
synced 2024-11-21 20:45:10 +00:00
Check if matrix is singular doing inverse (#49)
* Check if matrix is singular doing inverse * add return bool type
This commit is contained in:
parent
a33d5fe9c8
commit
f0a7984f39
@ -21,4 +21,12 @@ class MatrixException extends \Exception
|
||||
{
|
||||
return new self('Column out of range');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return MatrixException
|
||||
*/
|
||||
public static function singularMatrix()
|
||||
{
|
||||
return new self('Matrix is singular');
|
||||
}
|
||||
}
|
||||
|
@ -233,6 +233,10 @@ class Matrix
|
||||
throw MatrixException::notSquareMatrix();
|
||||
}
|
||||
|
||||
if ($this->isSingular()) {
|
||||
throw MatrixException::singularMatrix();
|
||||
}
|
||||
|
||||
$newMatrix = [];
|
||||
for ($i = 0; $i < $this->rows; ++$i) {
|
||||
for ($j = 0; $j < $this->columns; ++$j) {
|
||||
@ -271,4 +275,12 @@ class Matrix
|
||||
|
||||
return new self($newMatrix, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isSingular() : bool
|
||||
{
|
||||
return 0 == $this->getDeterminant();
|
||||
}
|
||||
}
|
||||
|
@ -141,6 +141,20 @@ class MatrixTest extends TestCase
|
||||
$matrix->inverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \Phpml\Exception\MatrixException
|
||||
*/
|
||||
public function testThrowExceptionWhenInverseIfMatrixIsSingular()
|
||||
{
|
||||
$matrix = new Matrix([
|
||||
[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
]);
|
||||
|
||||
$matrix->inverse();
|
||||
}
|
||||
|
||||
public function testInverseMatrix()
|
||||
{
|
||||
//http://ncalculators.com/matrix/inverse-matrix.htm
|
||||
|
Loading…
Reference in New Issue
Block a user