1

我正在尝试在我的一些代码中实现 k 最近邻函数。我遇到了一个我无法理解的相当奇怪的问题。让

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

我已经对此进行了测试,通常 knnsearch(X,Y) 将返回 Y 中的给定元素,即X中的最近邻居。但是当然 '7' 根本不是 X 中的一个元素,但是 knnsearch(X,8) 返回 7。我错过了什么吗?

4

2 回答 2

3

它返回索引不是元素本身。

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

nn保存索引(在本例中为2)。

所以X(nn)会给你12,这是预期的答案。

于 2013-02-18T18:23:29.643 回答
1

文档

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不返回最近的邻居,它返回最近邻居的索引。在您的示例中,6是最接近 的元素8,并且它位于 index 7,因此您得到7.

于 2013-02-18T18:23:09.847 回答