MATLAB: Finding the 10 nearest points to every point (with corresponding distances) within a single variable

distances to neighborsnearest points

Hi,
I need to find the 10 nearest points (with distances) to every other point within a group of points (i.e., 10 nearest neighrbors). Attached is the file containing all the points in question. I have previously tried to use "knnsearch" but to no avail. Can anyone produce the code that will do what I need?
Any help you could offer would be greatly appreciated.
Thanks,
Steve D.

Best Answer

After loading F_points, select one of the points by indicating its row index in the variable "pt". This solution computes the euclidean distance between that target point and all other points and then selects the 10 closest points. It then plots the results.
The index of all coordinates in order of proximity to the target point is stored in ascendIdx. The coordinates for the closest 10 points is stored in xyNearest.
xy = cell2mat(F_points)'; %[n x 2] matrix of (x,y) coordinates

pt = 20; % choose a target point in xy and we'll find the 10 nearest neighbors.
% Euclidean distance between xy(p,:) and all other points
dist = sqrt((xy(:,1)-xy(pt,1)).^2 + (xy(:,2)-xy(pt,2)).^2);
% Find the n closest values (excluding the point selected)
n = 10;
[~, ascendIdx] = sort(dist);
ascendIdx(ascendIdx==pt) = []; %remove the pt point
xyNearest = xy(ascendIdx(1:n),:);
% Plot
figure()
plot(xy(:,1),xy(:,2),'bo')
hold on
% Show the selected point
plot(xy(pt,1),xy(pt,2),'bo','MarkerFaceColor', 'y')
% Show nearest 'n' dots
plot(xyNearest(:,1),xyNearest(:,2),'r+')
% draw lines betwween target point and neightbors
% (not shown in figure below)
plot([xy(pt,1)*ones(n,1), xyNearest(:,1)]',...
[xy(pt,2)*ones(n,1), xyNearest(:,2)]', 'k-')
Results when pt = 20. The yellow dot is the one selected, the red + indicate the 10 closest neighbors.
[update]
To apply that for every point rather than just for one selected point, dist(n,m) below is a square matrix of the distance between point xy(n,:) and xy(m,:). ascendIdx is a square matrix of index values for each coordinate, sorted by closest distances. So, ascendIdx(p,q) is row index of q_th furthest point from xy(p,:).
xy = cell2mat(F_points)'; %[n x 2] matrix of (x,y) coordinates
dist = cell2mat(arrayfun(@(i)sqrt((xy(:,1)-xy(i,1)).^2 + (xy(:,2)-xy(i,2)).^2), 1:size(xy,1), 'UniformOutput', false));
n = 10;
[~, ascendIdx] = sort(dist);
See comments below for a comparison between this method and knnsearch() which is much slower.