MATLAB Answers

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

조회 수: 21(최근 30일)
Vance Blake
Vance Blake 2019년 8월 23일
댓글: Vance Blake 2019년 9월 1일
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
CTR Demo Incomplete 3.PNG

채택된 답변

Adam Danz
Adam Danz 2019년 8월 23일
편집: Adam Danz 2019년 8월 23일
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

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by