Finding the 10 nearest points to every point (with corresponding distances) within a single variable
Show older comments
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.
2 Comments
the cyclist
on 30 Sep 2019
Edited: 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
Accepted Answer
More Answers (1)
meghannmarie
on 30 Sep 2019
Edited: meghannmarie
on 30 Sep 2019
1 vote
Try this:
load('F_points.mat')
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.
2 Comments
Steve
on 30 Sep 2019
meghannmarie
on 1 Oct 2019
Edited: 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.
load('F_points.mat')
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
plot(xy(S(n).nearestIdx,1),xy(S(n).nearestIdx,2),'r*')
savefig(h,['pt_' num2str(n,'%03.0f') '.fig'])
close(h)
end
Categories
Find more on Nearest Neighbors in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
