# Drawing lines from 2 or more separate points to one target point and calculating the distance between them

7 views (last 30 days)
Vance Blake on 23 Aug 2019
Commented: Vance Blake on 1 Sep 2019
Hello, I have a plot where I create random points scattered around a set of central points. I am trying to draw lines from the 2 central points to another target point,. There will be more central points than 2 in the future so an adaptable solution is preferred. After drawing the lines, I need to calculate the distance between each point and the target point, find the minimum distance value and keep the line associated with the minimum distance value and delete the longer one. Below Ive included a picture of the basic situation. I line A is longer than line B then I will keep line B and vice versa. I need to be able to do this for every point on the graph and hopefully simultaneously. I also included the test code I am using to draw lines between one central point and one target but I havent been able to tweak it properly for multiple points.
for i = 1:LengthB
x2(i) = B(i,1);
y2(i) = B(i,2);
Line_matrix1(i,:) = line([x0, x2(i)],[y0, y2(i)], 'linewidth', 1.5, 'color', 'r');
drawnow;
hold on
end #### 1 Comment

darova on 23 Aug 2019

Adam Danz on 23 Aug 2019
Edited: Adam Danz on 23 Aug 2019
Use pdist2() to compute the distance between point p and points q. Compute the minimum distance and then plot that line (no need to plot all lines to find the distances).
% define point p and points [q]
p = [2,3]; %[x,y]
q = [7,3; %[x,y]
5,4;
1,5];
% Compute distance between point p and points [q]
dist = pdist2(p,q);
% Find shortest distance; minDistIdx will be the row number in q
[minDist, minDistIdx] = min(dist);
% Plot shortest line
plot([p(1),q(minDistIdx,1)], [p(2),q(minDistIdx,2)])

Vance Blake on 1 Sep 2019
Hey Adam, if you have time could you please help me with this question I have asked in the link below. I wanted to go to you directly because you have the full code and understand the general idea of what im trying to do. I use the pdist2() function you've shown above to calculate the distances between the points in each matrix but I want to sort the existing HS based on which vein node they are closest too. So if a particular HS is closer to one vein node than all the other vein nodes then the hormone seed goes to a new matrix. Basically, after the sorting is done all the existing HS are sorted based on the vein node they are closest to into separate matricies. Thanks for all your help.
Adam Danz on 1 Sep 2019
done.
Vance Blake on 1 Sep 2019