# Does knnsearch guarantee points in ascending distance order?

1 view (last 30 days)
Dang Manh Truong on 12 Dec 2016
Hi, I need to find the k-nearest neihgbors of a test point, but I also need to be sure that they are sorted in ascending order too. I have read the doc here: https://www.mathworks.com/help/stats/knnsearch.html There is this part when you use 'K' for name-value pair arguments: " IDX and D are my-by-K matrices. D sorts the distances in each row in ascending order. Each row in IDX contains the indices of the K closest neighbors in X corresponding to the K smallest distances in D. " It says that "D sorts sorts the distances in each row in ascending order" so IDX must be in ascending order as well right? I tried a simple script:
>> clear
>> Y = [0 0];
X = [100 10; 1 2; 0 3; 7 4; 10 2020; 30 27];
>> [idx,dist]=knnsearch(X,Y,'K',4)
idx =
2 3 4 6
dist =
2.2361 3.0000 8.0623 40.3609
>>
It appears to be sorted. But can I be sure that X(idx(1),:) is the 1st-nearest neighbor, X(idx(2),:) is the 2nd-nearest neighbor, and so on? Please help me, thank you very much :)