55 views (last 30 days)

I need to find closest point to A=[X2,Y2] among ListofNodes=[X1,Y1; X2,Y2; X3,Y3; ...], and I need to draw a line joining A and the closest point. I am using the following code:

A = [X2,Y2];

%compute Euclidean distances:

distances = sqrt(sum(bsxfun(@minus, ListofNodes , A).^2,2));

%find the smallest distance and use that as an index into ListofNodes:

closest = ListofNodes(distances==min(distances),:);

%draw a line joining the point and the closest coordinates

h = line(A,closest);

set(h, 'LineWidth', 0.01, 'Color','blue');

The problem is that ListofNodes also contains A. So, I am getting closest = A. How to solve this problem?

KSSV
on 31 Jul 2018

Edited: KSSV
on 31 Jul 2018

Have a look on knnsearch. It will give you what you want.

A = rand(10,2) ;

idx = knnsearch(A,A(2,:),'k',2) ; % get two close points

idx(1) = [] ; % remove the pomnt itself

plot(A(:,1),A(:,2),'.r') ;

hold on

plot(A(2,1),A(2,2),'Ob') ;

plot([A(2,1), A(idx,1)],[A(2,2), A(idx,2)])

Opportunities for recent engineering grads.

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

Start Hunting!
## 3 Comments

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/412842-find-closest-coordinates-to-a-point-from-a-list-of-coordinates-where-the-list-also-contains-that-poi#comment_595001

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/412842-find-closest-coordinates-to-a-point-from-a-list-of-coordinates-where-the-list-also-contains-that-poi#comment_595001

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/412842-find-closest-coordinates-to-a-point-from-a-list-of-coordinates-where-the-list-also-contains-that-poi#comment_595009

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/412842-find-closest-coordinates-to-a-point-from-a-list-of-coordinates-where-the-list-also-contains-that-poi#comment_595009

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/412842-find-closest-coordinates-to-a-point-from-a-list-of-coordinates-where-the-list-also-contains-that-poi#comment_595010

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/412842-find-closest-coordinates-to-a-point-from-a-list-of-coordinates-where-the-list-also-contains-that-poi#comment_595010

Sign in to comment.