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 i = k+1:m for j = 1:n [c, ci] = tail(DD); % calculate candidate and canditate index if disMat(i,j) < c(j) DD() end end end I = II.'; D = DD.'; end