MATLAB Answers

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

97 views (last 30 days)
Steve on 30 Sep 2019
Commented: Adam Danz on 28 Feb 2020
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.
Steve D.


the cyclist
the cyclist on 30 Sep 2019
I don't see an attachment. (A *.mat file would be most useful.) Also, describing the exact output shape/size will probably be useful as well.
Steve on 30 Sep 2019
Thanks for your response. I need to store the 10 closest (indexed) points to every set of coordinates contained in the attached file. Each set of 10 points should be specified with index numbers, so that they can be plotted along with their "source" point. For example point 1, could be plotted with its 10 closest points. Hope this helps.

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 30 Sep 2019
Edited: Adam Danz on 1 Oct 2019
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
hold on
% Show the selected point
plot(xy(pt,1),xy(pt,2),'bo','MarkerFaceColor', 'y')
% Show nearest 'n' dots
% 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.
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.


Show 4 older comments
Adam Danz
Adam Danz on 1 Oct 2019
Comparison between the lower-level solution and knnsearch()
Below is an implementation of knnsearch() compared to the lower-level solution in my answer. They both produce the same output.
% load the data
xy = F_points.';
pt = 50; % identify target point (row number of xy)
n = 10; % number of nearest neighbors
% knnsearch method
xyTemp = xy(~ismember(1:size(xy,1),pt),:); %remove the target point from the list
nnidx = knnsearch(xyTemp,xy(pt,:),'K',n); %find row index of nearest neighbors
xyNearest1 = xyTemp(nnidx,:); %store coordinates of NN
% lower level method
dist = sqrt((xy(:,1)-xy(pt,1)).^2 + (xy(:,2)-xy(pt,2)).^2); %distance to each point
[~, ascendIdx] = sort(dist); % sort distances
ascendIdx(ascendIdx==pt) = []; % remove the pt point
xyNearest2 = xy(ascendIdx(1:n),:); % store coordinates of NN
% show that the results match
To compare speeds between these methods, I ran each of them 10k times and recorded the execution time using tic/toc. According to the median speeds, the lower level method was 30x faster than knnsearch().
Konstantina Bantra
Konstantina Bantra on 28 Feb 2020
I have a very similar problem and I was wondering how would you loop through each point to extract each time the 10 closest points and specifically how you would set the value for pt in each loop iteration .
Adam Danz
Adam Danz on 28 Feb 2020
I think what you're looking for is the "update" section of my answer where you can apply the algorithm to every point to find the 10 closest points.
If you really want a loop, you can easily embed the first part of the answer within a for-loop.

Sign in to comment.

More Answers (1)

meghannmarie on 30 Sep 2019
Edited: meghannmarie on 30 Sep 2019
Try this:
f = cell2mat(F_points)';
Mdl = KDTreeSearcher(f);
[idx,distance] = knnsearch(Mdl,f,'k',11);
idx = idx(:,2:end);
distance = distance(:,2:end);
Each row in idx ocorresponds to the 10 closest points in each row in f. The first column is removed because that is the point itself so I search to 11 closest points.


Steve on 30 Sep 2019
Thank you for the input. How do I know which point is associated to each row? Also, Can I plot each point along with their 10 neighbors? Thanks again.
meghannmarie on 1 Oct 2019
I put the data in a structure so you could see points with corresponding index to nearest neightbors and the distances.
The plot function here plots each point and its 10 neighbors in a separate figure and saves it. (is that what you want?) .This will save 953 figures in your working folder.
T = table();
T.xy = cell2mat(F_points)';
Mdl = KDTreeSearcher(f);
[idx,distance] = knnsearch(Mdl,xy,'k',11);
T.nearestIdx = idx(:,2:end);
T.nearestDistance = distance(:,2:end);
S = table2struct(T);
for n = 1:size(xy,1)
% Plot
h = figure();
plot(S(n).xy(1),S(n).xy(2),'bo','MarkerFaceColor', 'y')
hold on
% Show nearest 'n' dots
savefig(h,['pt_' num2str(n,'%03.0f') '.fig'])

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!