PseudoInverse { public static Matrix pseudoInverse(Matrix matrix) { no.uib.cipr.matrix.DenseMatrix mjtA = new no.uib.cipr.matrix.DenseMatrix(matrix.getArray()); no.uib.cipr.matrix.SVD svd; try { svd = no.uib.cipr.matrix.SVD.factorize(mjtA); } catch (NotConvergedException e) { throw new RuntimeException(e); } Matrix Sinv = new Matrix(matrix.getColumnDimension(), matrix.getRowDimension()); double[] Sarr = svd.getS(); for (int i=0; i<svd.getS().length; i++) { Sinv.set(i, i, 1.0 / Sarr[i]); } Matrix Vt = new Matrix(svd.getVt().numRows(), svd.getVt().numColumns()); for (int r=0; r<svd.getVt().numRows(); r++) { for (int c=0; c<svd.getVt().numColumns(); c++) { Vt.set(r,c, svd.getVt().get(r, c)); } } Matrix U = new Matrix(svd.getU().numRows(), svd.getU().numColumns()); for (int r=0; r<svd.getU().numRows(); r++) { for (int c=0; c<svd.getU().numColumns(); c++) { U.set(r,c, svd.getU().get(r, c)); } } Matrix pinv = Vt.transpose().times(Sinv).times(U.transpose()); return pinv; }  static Matrix pseudoInverse(Matrix matrix); static Matrix pseudoInverse(Matrix matrix, int rank); static Matrix pseudoInverse(ch.akuhn.matrix.Matrix matrix, int rank);  }
@Test public void testPinv() { Matrix p = PseudoInverse.pseudoInverse(matrix); assertTrue(MatrixUtils.equals(p, pinv, 0.05)); Matrix pp = PseudoInverse.pseudoInverse(p); assertTrue(MatrixUtils.equals(pp, matrix, 0.00001)); }
@Test public void testPinvRnk3() { Matrix p = PseudoInverse.pseudoInverse(matrix, 3); assertTrue(MatrixUtils.equals(p, pinv, 0.05)); }
@Test public void testPinvRnk2() { Matrix p = PseudoInverse.pseudoInverse(matrix, 2); assertTrue(MatrixUtils.equals(p, pinvRnk2, 0.05)); }
@Test public void testPinvRnk1() { Matrix p = PseudoInverse.pseudoInverse(matrix, 1); assertTrue(MatrixUtils.equals(p, pinvRnk1, 0.05)); }