MATLAB: How to find k nearest vectors from a given vector in 3 dimensions

nearest neighbor

I have a reference vector and I want to find a fixed k nearest neighbors from a matrix ? How can I do it? Is there any direct way?

Best Answer

This is one way:
V = randi(50, 1, 3); % Vector
M = randi(50, 15, 3); % Matrix
%
dif = bsxfun(@minus, V, M); % Subtract Vector from Matrix
D = sqrt(sum(dif.^2,2)); % Euclidean Distance Metric
[Ds,Ix] = sort(D,'ascend'); % Sort Ascending
k = 5; % Number Of Neighbours
KNN = M(Ix(1:k),:); % K-th Nearest Neighbours
This simply finds them. If you have the Statistics Toolbox, the pdist2 function is likely more efficient.
Related Question