Calculating Mahalanobis distance with C#

2019-05-29 05:49发布

I'm trying to calculate the mahalanobis distance with c#. I can't find any real good examples online and I'm new to C#. I am especially having trouble getting the covariance matrix to run right. Any help would be appreciated. Thanks!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra.Double;

namespace MahalanobisDistance
 {
   class Program
{

    static void Main(string[] args)
    {
        Program p = new Program();
        DenseVector vector1 = new DenseVector(4);
        DenseVector vector2 = new DenseVector(4);
        DenseMatrix matrix1 = new DenseMatrix(vector1.Count/2);

        vector1[0] = 1;
        vector1[1] = 2;
        vector1[2] = 3;
        vector1[3] = 4;

        vector2[0] = 2;
        vector2[1] = 12;
        vector2[2] = 14;
        vector2[3] = 18;

        matrix1 = p.twoPassCovariance(vector1, vector2);
        for(int i = 0; i < matrix1.RowCount; i++)
        {
            for(int k = 0; k < matrix1.ColumnCount; k++)
            {

                Console.Write(matrix1[k, i] + " ");
            }
            //Mahalanobis2(v1, v2, covariance);
            Console.Write("\n");
        }
    }

    public DenseMatrix twoPassCovariance(DenseVector data1, DenseVector data2)
    {
        int n = data1.Count;

        double mean1 = data1.Average();
        double mean2 = data2.Average();

        DenseMatrix covariance = new DenseMatrix(data1.Count);
        double x;

        for(int i = 0; i < 2; i++)
        {
            for (int k = 0; k < n; k++)
            {
                double a = data1[i] - mean1;
                double b = data2[k] - mean2;
                x = a*b;
                covariance[i, k] = x;
            }
        }

        covariance.Multiply(1/n);
        return covariance;
    }

}}

1条回答
2楼-- · 2019-05-29 05:54

In the i loop in the twoPassCovariance method, I believe you should loop to i < n rather than i < 2.

查看更多
登录 后发表回答