I have a set of points, representing location of events in a map, and I want to find the closest neighbour for each point. Variable xys
is a 2D matrix containing the set of coordinates for each point (column 1 for x- and column 2 for y-coordinate).
xys = Table[RandomReal[{1, 9000}], {rr, 1, 300}, {cc, 1, 2}]
To calculate the distance I come up with two approaches:
Approach 1
Table[ ArcLength[Line[{xys[[jj]], xys[[ii]]}]], {ii, 1, Length[xys]}, {jj, 1, Length[xys]}]
{21.8557, Null}
Approach 2
Table[Sqrt[(xys[[1, 1]] - xys[[ii, 1]])^2 + (xys[[1, 2]] - xys[[ii, 2]])^2], {ii, 1, 1000}];
{0.468003, Null}
Approach 1 quite inefficient: for calculating 300 points, it takes 21 sec. Approach 2 is almost two order of magnitude faster, at 0.4 sec.
What I would like to understand is why is there such a big difference. I thought ArcLength[Line[...]] would be the faster and more efficient since it uses Mathematica functions. Since my real data set ultimately will be 10000-30000 points, the whole process will end up to be quite long even with the second approach. Therefore I would be grateful if anyone could suggest an even more efficient and faster approach.
Thanks,
Nearest
(as noted by others) with Euclidean distance, and postprocess to get geodistances between relevant pairs. This will work correctly if all points are in the same hemisphere. $\endgroup$