参考官方文档学习,英文部分是官方文档的描述
1、IDX = knnsearch(X,Y)
IDX = knnsearch(X,Y) finds the nearest neighbor in X for each point in Y. IDX is a column vector with my rows. Each row in IDX contains the index of nearest neighbor in X for the corresponding row in Y.
在X中,为Y的每一个点找最近邻居。其中,IDX是一个列向量,每一行表示的是Y在X中的最近邻所对应的在X中的索引值。
clc
X = [1 2;
3 1;
5 8;
4 10;
7 4];
Y = [5 7;
1 3];
IDX = knnsearch(X,Y);
disp(IDX);
在这个例子中,y的两个点在x中的最近邻分别是第三个和第一个。所以会返回在x中的索引 3和1.
2、[IDX,D] = knnsearch(X,Y)
returns an my-by-1 vector D containing the distances between each observation in Y and the corresponding closest observation in X. That is, D(i) is the distance between X(IDX(i),:) and Y(i,:)
IDX 同上述表示一样,D返回的是Y在X中的最近邻与Y的距离。
3、[IDX,D] = knnsearch(X,Y,'Name',Value)
accepts one or more optional comma-separated name-value pair arguments. Specify Name inside single quotes. knnsearch does not save a search object.
clc
X = [1 2;
3 1;
5 8;
4 10;
7 4];
Y = [5 7;
8 5];
[IDX,D] = knnsearch(X,Y,'k',3);
disp(IDX);
disp(D);
以这个例子为例,有两个Y,表达式3表示的是为每个Y找三个最近邻。
这个的意思还是与上面表达的一样。需要解释的是位置关系的事,我们拿距离D来解释。有两个Y所以有两行,每个Y找三个最近邻,所以一行有三个,在这里,距离按照从小到大排序。