简体   繁体   中英

knnsearch(X,Y) not returning an element of X

I am trying to implement a k-nearest neighbors function in some of my code. I am running into a rather strange issue that I cannot understand. Let

X=[1,4,51,3,2,4,6]' % a column vector
knnsearch(X,8) %returns 7!

I have tested this out and usually knnsearch(X,Y) will return for a given element in Y, the nearest neighbor in X . But of course '7' is not an element in X at all, but knnsearch(X,8) is returning 7. Am I missing something?

It returns the index and not the element itself.

>> X = [1, 12, 33, 14]';
>> nn = knnsearch(X, 8);
>> X(nn) %Will print 12

nn holds the index (in this case it is 2 ).

So X(nn) will give you 12 , which is the expected answer.

From the docs :

IDX = knnsearch(NS,Y)

[...]

IDX is a column vector with ny rows, where ny is the number of rows in Y. 
Each row in IDX contains the index of observation in NS.X which has the 
smallest distance to the corresponding observation in Y.

knnsearch doesn't return the nearest neighbour, it return the index of the nearest neighbour. In your example, 6 is the closest element to 8 , and it's at index 7 , so you get 7 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM