how to find k-th nearest neighbor of a point

3 views (last 30 days)
Rana Sobhy
Rana Sobhy on 10 Jun 2016
Commented: MA-Winlab on 29 Mar 2019
i have many rectangles in the image represented by its centriod. How can i calculate the 10th nearest neighbor rectangles (centroids) for each ?

Answers (2)

Image Analyst
Image Analyst on 10 Jun 2016
Here's a way to do it if you don't have the Stats toolbox.
% Create sample data.
x = rand(1,100);
y = rand(1,100);
% Now we can start.
% Find number of centroid points.
numPoints = length(x);
% Make an array to keep track of the index of the 10th closest
% and that 10th closest point's index in the array.
tenthClosest = zeros(numPoints, 2);
for k = 1 : numPoints
% Compute the distances of kth point to every other point (including itself).
distances = sqrt((x(k)-x).^2 + (y(k) - y).^2);
% Sort them so we can get the 10th distance at index 11
% since there will be one point at 0 which is the distance of the point to itself which we don't care about.
[sortedDistances, sortOrder] = sort(distances, 'Ascend');
tenthClosest(k, 1) = sortedDistances(11);
tenthClosest(k, 2) = sortOrder(11);
end
% Print to command window
tenthClosest

KSSV
KSSV on 10 Jun 2016
doc knnsearch

Community Treasure Hunt

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

Start Hunting!