Pawcu
Pawcu

Reputation: 322

C# array distance function

Is there any simple way to calculate some sort of distance function on 2 arrays of the same length so as to check their difference? The arrays are both float and each bin may be empty or contain a value. I am doing this since I need to compare two color histograms of 2 different images. Thank you

Edit: By distance function I mean something like Levenshtein distance on the two arrays so I can check the 'difference' between. I was hoping to check whether the object is in the image according to the distance calculated.

Upvotes: 1

Views: 1271

Answers (2)

Pawcu
Pawcu

Reputation: 322

Ended up using a simple for loop to iterate through each item:

private static float ArrayDistanceFunction(float[] array1, float[] array2)
{
        float total = 0;

        for (int i = 0; i < array1.Length; i++)
        {
            total += Math.Abs(array1[i] - array2[i]);
        }
        return total;
}

Reed Copsey's answer does work but somehow it behaved slower than my implementation

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564691

If you just want the sum of the differences between the individual values, you could use:

var distance = array1.Zip(array2, (a,b) => Math.Abs(a-b)).Sum();

Upvotes: 1

Related Questions