Mahalanobis { public static double distance(RealMatrix m1, double v1[], double v2[]) { double det = Math.pow((new LUDecompositionImpl(m1).getDeterminant()), 1/(v1.length)); double[] tempSub = new double[v1.length]; for(int i=0; i < v1.length; i++){ tempSub[i] = (v1[i]-v2[i]); } double[] temp = new double[v1.length]; for(int i=0; i < temp.length; i++){ temp[i] = tempSub[i]*det; } RealMatrix m2 = new Array2DRowRealMatrix(new double[][] { temp }); RealMatrix m3 = m2.multiply(new LUDecompositionImpl(m1).getSolver().getInverse()); RealMatrix m4 = m3.multiply((new Array2DRowRealMatrix(new double[][] { temp })).transpose()); return Math.sqrt(m4.getEntry(0, 0)); }  static double distance(RealMatrix m1, double v1[], double v2[]);  }
@Test public void test01() { double[] v1 = new double[] {1, 12, 5}; double[] v2 = new double[] {1, 12, 5}; RealMatrix m1 = new Array2DRowRealMatrix(new double [][] { {10.70, -17.95, 1.55}, {-17.95, 44.20, 0.95}, {1.55, 0.95, 3.70} }); Asserts.assertEqualLength(v1, v2); double res = Mahalanobis.distance(m1, v1, v2); Asserts.assertEquals(res, 0); }
@Test public void test02() { double[] v1 = new double[] {1, 12, 5}; double[] v2 = new double[] {0, 14, 7}; RealMatrix m1 = new Array2DRowRealMatrix(new double[][] { {10.70, -17.95, 1.55}, {-17.95, 44.20, 0.95}, {1.55, 0.95, 3.70} }); Asserts.assertEqualLength(v1, v2); double res = Mahalanobis.distance(m1, v1, v2); Asserts.assertEquals(res, 1.323220219); }
@Test public void test03() { double[] v1 = new double[] {1, 12, 5}; double[] v2 = new double[] {8, 0, 6}; RealMatrix m1 = new Array2DRowRealMatrix(new double[][] { {10.70, -17.95, 1.55}, {-17.95, 44.20, 0.95}, {1.55, 0.95, 3.70} }); Asserts.assertEqualLength(v1, v2); double res = Mahalanobis.distance(m1, v1, v2); Asserts.assertEquals(res, 2.141290741); }
@Test public void test04() { double[] v1 = new double[] {1, 12, 5}; double[] v2 = new double[] {2, 2, 3}; RealMatrix m1 = new Array2DRowRealMatrix(new double[][] { {10.70, -17.95, 1.55}, {-17.95, 44.20, 0.95}, {1.55, 0.95, 3.70} }); Asserts.assertEqualLength(v1, v2); double res = Mahalanobis.distance(m1, v1, v2); Asserts.assertEquals(res, 2.238505943); }
@Test public void test05() { double[] v1 = new double[] {1, 12, 5}; double[] v2 = new double[] {5, 1, 8}; RealMatrix m1 = new Array2DRowRealMatrix(new double[][] { {10.70, -17.95, 1.55}, {-17.95, 44.20, 0.95}, {1.55, 0.95, 3.70} }); Asserts.assertEqualLength(v1, v2); double res = Mahalanobis.distance(m1, v1, v2); Asserts.assertEquals(res, 2.748198002); }