2/19/2013

Mahalanobis distance source code between 2D normal distributions

Mahalanobis distance source code between 2D normal distributions

The formula to calculate malanobis distance from 2 distributions is follows:




This is source code

struct mean_cov{
    float mean11;
    float mean21;

    float cov11;
    float cov12;
    float cov21;
    float cov22;
};


float Dist_2Distribution( mean_cov mc1, mean_cov mc2 )
{

    float a,b,c,d;

    float A = (mc1.mean11 - mc2.mean11);
    float B = (mc1.mean21 - mc2.mean21);

    float e = 1/((mc1.cov11 + mc2.cov11)*(mc1.cov22 + mc2.cov22) - (mc1.cov12 + mc2.cov12)*(mc1.cov21 + mc2.cov21));

    a = e * (mc1.cov22 + mc2.cov22);
    b = e * -(mc1.cov12 + mc2.cov12);
    c = e * -(mc1.cov21 + mc2.cov21);
    d = e * (mc1.cov11 + mc2.cov11);

    

    return ((a*A + c*B)*A + (b*A + d*B)*B);
}