diff --git a/src/main/java/org/apache/commons/math3/linear/MatrixUtils.java b/src/main/java/org/apache/commons/math3/linear/MatrixUtils.java index 1f9b1b5ae..5b917805b 100644 --- a/src/main/java/org/apache/commons/math3/linear/MatrixUtils.java +++ b/src/main/java/org/apache/commons/math3/linear/MatrixUtils.java @@ -1023,18 +1023,34 @@ public class MatrixUtils { final RealMatrix d = m.getSubMatrix(splitIndex1, n - 1, splitIndex1, n - 1); final SingularValueDecomposition aDec = new SingularValueDecomposition(a); - final RealMatrix aInv = aDec.getSolver().getInverse(); + final DecompositionSolver aSolver = aDec.getSolver(); + if (!aSolver.isNonSingular()) { + throw new SingularMatrixException(); + } + final RealMatrix aInv = aSolver.getInverse(); final SingularValueDecomposition dDec = new SingularValueDecomposition(d); - final RealMatrix dInv = dDec.getSolver().getInverse(); + final DecompositionSolver dSolver = dDec.getSolver(); + if (!dSolver.isNonSingular()) { + throw new SingularMatrixException(); + } + final RealMatrix dInv = dSolver.getInverse(); final RealMatrix tmp1 = a.subtract(b.multiply(dInv).multiply(c)); final SingularValueDecomposition tmp1Dec = new SingularValueDecomposition(tmp1); - final RealMatrix result00 = tmp1Dec.getSolver().getInverse(); + final DecompositionSolver tmp1Solver = tmp1Dec.getSolver(); + if (!tmp1Solver.isNonSingular()) { + throw new SingularMatrixException(); + } + final RealMatrix result00 = tmp1Solver.getInverse(); final RealMatrix tmp2 = d.subtract(c.multiply(aInv).multiply(b)); final SingularValueDecomposition tmp2Dec = new SingularValueDecomposition(tmp2); - final RealMatrix result11 = tmp2Dec.getSolver().getInverse(); + final DecompositionSolver tmp2Solver = tmp2Dec.getSolver(); + if (!tmp2Solver.isNonSingular()) { + throw new SingularMatrixException(); + } + final RealMatrix result11 = tmp2Solver.getInverse(); final RealMatrix result01 = aInv.multiply(b).multiply(result11).scalarMultiply(-1); final RealMatrix result10 = dInv.multiply(c).multiply(result00).scalarMultiply(-1); diff --git a/src/test/java/org/apache/commons/math3/linear/MatrixUtilsTest.java b/src/test/java/org/apache/commons/math3/linear/MatrixUtilsTest.java index 6aa973b8a..8ae0a41cc 100644 --- a/src/test/java/org/apache/commons/math3/linear/MatrixUtilsTest.java +++ b/src/test/java/org/apache/commons/math3/linear/MatrixUtilsTest.java @@ -364,6 +364,18 @@ public final class MatrixUtilsTest { } } + @Test(expected=SingularMatrixException.class) + public void testBlockInverseNonInvertible() { + final double[][] data = { + { -1, 0, 123, 4 }, + { -56, 78.9, -0.1, -23.4 }, + { 5.67, 8, -9, 1011 }, + { 5.67, 8, -9, 1011 }, + }; + + MatrixUtils.blockInverse(new Array2DRowRealMatrix(data), 2); + } + @Test public void testIsSymmetric() { final double eps = Math.ulp(1d);