Search code examples
c#kinecttoolbox

kinect toolbox c# syntax


I have been studying the algorithm used in kinect toolbox to compare vector sequences, but I am struggling to understand this piece of code:

 public static float DistanceTo(this List<Vector2> path1, List<Vector2> path2)
    {
        return path1.Select((t, i) => (t - path2[i]).Length).Average();
    }

as far as I understand this takes two sequences of 2d vectors and computes the distance between them by means of euclidean distance, that is, it calculates the length of the difference between vectors, I however had never seen the syntax inside the parenthesis, specially the =>.

Any insight would be much appreciated.


Solution

  • You can simply unroll this select statement.

    path1.Select((t, i) => (t - path2[i]).Length) iterates over path1, for every element in it, it selects the Vector2 element and its index in the path1 list.

    From that intermediate result it will do the difference between the two corresponding vectors at the same index (t - path2[i]), where - is a parameter overload for the vector substraction method. From that difference it will calculate the vector length which is basically just a squared(?) summation over its elements.

    Average() in the end just takes the average over all the given vector differences.

    This C# code is semantically the same:

    float sum = 0.0f;
    for(int i = 0; i < path1.Count; i++)
    {
       sum += (path1[i] - path[2]).Length;
    }
    return sum / (float)path1.Count;
    

    Or even nicer as a LINQ zip expression:

    path1.Zip(path2, (left, right) => (left-right).Length).Average();