From f0a7984f39f552363a03b6a2bb62b8b5ae65e218 Mon Sep 17 00:00:00 2001 From: Povilas Susinskas Date: Wed, 15 Feb 2017 11:09:16 +0200 Subject: [PATCH] Check if matrix is singular doing inverse (#49) * Check if matrix is singular doing inverse * add return bool type --- src/Phpml/Exception/MatrixException.php | 8 ++++++++ src/Phpml/Math/Matrix.php | 12 ++++++++++++ tests/Phpml/Math/MatrixTest.php | 14 ++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/src/Phpml/Exception/MatrixException.php b/src/Phpml/Exception/MatrixException.php index 9aaa43a..2815804 100644 --- a/src/Phpml/Exception/MatrixException.php +++ b/src/Phpml/Exception/MatrixException.php @@ -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'); + } } diff --git a/src/Phpml/Math/Matrix.php b/src/Phpml/Math/Matrix.php index 6485a7d..39f5c5a 100644 --- a/src/Phpml/Math/Matrix.php +++ b/src/Phpml/Math/Matrix.php @@ -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(); + } } diff --git a/tests/Phpml/Math/MatrixTest.php b/tests/Phpml/Math/MatrixTest.php index b4adc76..48a6fe9 100644 --- a/tests/Phpml/Math/MatrixTest.php +++ b/tests/Phpml/Math/MatrixTest.php @@ -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