MATLAB: Results of knnsearch do not make sense (to me)

knnsearchnearest neighbor

Hello,
I am using [IDX,D] = knnsearch(y,y,'K',2,'NSMethod','exhaustive') to find the nearest neighbor to each point of y in y (excluding obviously the same point, hence the 2 in 'K').
The algorithm returns that point 34 is the nearest neighbor of point 72, but when one goes to point 72, its nearest neighbor is point 124 (I guess it should be point 34). Any clue why this happens?

Best Answer

point 34 is the nearest neighbor of point 72, but when one goes to point
72, its nearest neighbor is point 124 (I guess it should be point 34).
There is no problem.
p3 = [-1.3907, 0.6324, 0.76023]
p4 = [-1.4093, 0.6363, 0.73788]
p5 = [-1.4140, 0.6371, 0.71772]
If p4 is the nearest point to p3, it can be valid that p5 is the nearest to p4. There is no logical problem. Try this with numbers:
[1, 3, 4]
Now 3 is the nearest point to 1, but the nearest point of 3 is not 1 but 4. So only your expectation was wrong.
By the way, you can expect, that such a well tested function of the Matlab toolbox like knnsearch does not reply rubbish. If the output "does not make sense", then this is a problem of the process of "making sense", not of the output. ;-)