Drawing lines from 2 or more separate points to one target point and calculating the distance between them
    9 views (last 30 days)
  
       Show older comments
    
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

Accepted Answer
  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)])
11 Comments
More Answers (0)
See Also
Categories
				Find more on Get Started with MATLAB 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!

