private double mahalanobisMethod(List <double> midValues, List <double> elementValues) { //var mainWindow = (MainWindow)Application.Current.MainWindow; //var format = new NumberFormatInfo(); //format.NegativeSign = "-"; //int i = 0; //double[,] table = new double[mainWindow.gridData.Rows.Count, mainWindow.gridData.Columns.Count - 1]; //foreach (DataRow row in mainWindow.gridData.Rows) //{ // for (int j = 0; j < mainWindow.gridData.Columns.Count - 1; j++) // { // var value = mainWindow.gridData.Rows[i][j].ToString(); // if (value.StartsWith(",") || value.StartsWith(".")) // { // value = "0" + value; // } // table[i, j] = Convert.ToDouble(value, format); // } // i++; //} //double[] d = new double[mainWindow.gridData.Columns.Count - 1]; //double[,] diff = new double[1, mainWindow.gridData.Columns.Count - 1]; //double[,] covarMatrix = table.Covariance(); //double[,] inverseCovarMatrix = null; //try //{ // inverseCovarMatrix = covarMatrix.Inverse(); //} //catch (Exception exp) //{ // inverseCovarMatrix = covarMatrix.PseudoInverse(); //} //var mahalanobis = Mahalanobis.FromPrecisionMatrix(inverseCovarMatrix); double result = mahalanobis.Distance(midValues.ToArray(), elementValues.ToArray()); if (Double.IsNaN(result)) { return(0); } else { return(result); } }
public void doc_mahalanobis() { #region doc_mahalanobis_3 // Let's say we would like to compute the Mahalanobis // distance between the two vectors x and y below: double[] x = { 2, 5, 1 }; double[] y = { 4, 2, 2 }; // Using the covariance double[,] covariance = { { 4, 3, 0 }, { 3, 5, 2 }, { 0, 2, 6 } }; // There are multiple ways to create a Mahalanobis // distance. The easiest method by far is by using: var mahalanobis = Mahalanobis.FromCovarianceMatrix(covariance); // Then, you can compute the distance using: double distance = mahalanobis.Distance(x, y); // However, if you need more control over how the covariance matrix // should be inverted, or if you have the precision matrix instead of // the covariance, you can use any of the alternative methods: var fromCholesky = new Mahalanobis(new CholeskyDecomposition(covariance)); var fromSVD = new Mahalanobis(new SingularValueDecomposition(covariance)); var fromPrecision1 = new Mahalanobis(covariance.Inverse()); var fromPrecision2 = Mahalanobis.FromPrecisionMatrix(covariance.Inverse()); // They all should produce equivalent results: double a = fromCholesky.Distance(x, y); double b = fromSVD.Distance(x, y); double c = fromPrecision1.Distance(x, y); double d = fromPrecision2.Distance(x, y); #endregion double expected = Distance.Mahalanobis(x, y, new CholeskyDecomposition(covariance)); Assert.AreEqual(3.5185224171518357, expected, 1e-10); Assert.AreEqual(expected, distance, 1e-10); Assert.AreEqual(distance, a, 1e-10); Assert.AreEqual(distance, b, 1e-10); Assert.AreEqual(distance, c, 1e-10); Assert.AreEqual(distance, d, 1e-10); }