2012-06-14 53 views
1

我想用c#計算馬氏距離。我在網上找不到任何真正的好例子,我是C#的新手。我特別難以使協方差矩陣正確運行。任何幫助,將不勝感激。謝謝!用C#計算馬氏距離

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

您是否有特定的問題或者您在尋找代碼審查? – bluevector

+1

你的載體非常非常小。您是否真的在調試器中逐行創建協變矩陣的代碼,以查看問題出在哪裏? – mathematician1975

回答

2

twoPassCovariance方法i循環,我相信你應該環路i < n而非i < 2