How to draw line between point and plotted line?
1 view (last 30 days)
Show older comments
I am trying to find a way to plot a line between a point to a plotted line, how can this be accomplished
My current code currently calculates the shortest distance from the point to the line, but I have not been able to figure out how to plot the shortest distance as a line.
x = 0:0.1:10;
y = 3*x + 2;
plot(x,y);
hold on;
x0 = 5;
y0 = 6;
a = 3;
b = -1;
c = 2;
distance = abs(a*x0+ b*y0 + c)/sqrt(a^2 + b^2);
hold off;
It draws this currently:
I am trying to make accomplish this:
0 Comments
Accepted Answer
Star Strider
on 16 Jan 2022
The two plots are different, so using the provided data (and the same Wikipedia article Distance from a point to a line) provides two additional relations for the point on the line (here ‘xi’ and ‘yi’) that is neareast to the point —
x = 0:0.1:10;
y = 3*x + 2;
x0 = 5;
y0 = 6;
a = 3;
b = -1;
c = 2;
xi = (b*(b*x0 - a*y0) - a*c) / (a.^2 + b.^2)
yi = (a*(-b*x0 + a*y0) - b*c) / (a.^2 + b.^2)
figure
plot(x,y);
hold on
plot([x0 xi], [y0 yi], '-or', 'MarkerFaceColor','r')
hold off
grid
axis('equal')
text(x0, y0, sprintf(' \\leftarrow (%.1f, %.1f)',x0, y0), 'Horiz','left', 'Vert','middle')
text(xi, yi, sprintf('(%.1f, %.1f) \\rightarrow ',xi, yi), 'Horiz','right', 'Vert','middle')
text(5, 17, sprintf('y = 3\\cdotx+2 \\rightarrow '), 'Horiz','right', 'Vert','middle')
.
0 Comments
More Answers (0)
See Also
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!