Finding the nearest neighboors of a point on a 2D plot

23 views (last 30 days)
Hasan Kaplan
Hasan Kaplan on 30 Jun 2021
Edited: Walter Roberson on 4 Jul 2021
Hello,
I am working on point cloud data and i converted the 3D data to 2D with avoiding Z values. (as plot(X(:,1),Y(:,2),'*')) On this 2D plot i want to find the distances between each point and k-neighboors of it. How can i use the findNearestNeighboors method for this 2D plot?
  2 Comments
Yazan
Yazan on 3 Jul 2021
@Image Analyst Apparently, I added my answer in the comment section by mistake. Thanks for the reminder!

Sign in to comment.

Accepted Answer

Yazan
Yazan on 3 Jul 2021
Edited: Walter Roberson on 4 Jul 2021
First of all, you have to define your distance. The Euclidean distance, for example?
Step1: Create nearest neighbor searcher object
% use cityblock as a distance, check the documentation for other distance
% measures
% xy is an N-by-2 matrix containing the X-axis and Y-axis values of your data
xy = [xval, yval] % ex: xy = randn(128, 2);
nso = createns(xy, 'Distance', 'cityblock');
Step 2: Find k-nearest neighbors using input data
% k is the number of nearest neighbors
[idx, distk] = knnsearch(nso, xy, 'k', k);
Output:
  • idx is an N-by-k matrix, where each row i is the indices of the k-neareghoest neighbors to xy(i,:)
  • Of course, the first column of idx is the indices of the data itself, as the closest point to a given datapoint is the point itself.
  • distk is an N-by-k matrix, where each row contains the respective k distances

More Answers (0)

Community Treasure Hunt

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

Start Hunting!