|
- function [I, D] = kNN(X, Y, k)
- %kNN return the k-nearest neighbors Of Y into dataset X
- %
- % Outputs:
- % I : [n x k] The indexes of X where the nearest neighbors of Y lies
- % D : [n x k] The distances of each neighbor
- %
- % Inputs:
- % X : [m x d] Corpus data points (d dimensions)
- % Y : [n x d] Query data points (d dimensions)
- % k : [scalar] The number of neighbors
-
- disMat = distXY(X, Y);
- [m, n] = size(disMat);
-
- II = repmat([1:k].', 1, n); % init the min algorithm
- DD = disMat(1:k,:);
- for j = 1:n
- for i = k+1:m
- % calculate candidate and canditate index
- [tail, taili] = maxIdx(DD(:, j));
- if disMat(i,j) < tail
- DD(taili, j) = disMat(i,j);
- II(taili, j) = i;
- end
- end
- end
- I = II.';
- D = DD.';
- end
|