Calculating the shortest distance of any given coordinate point to the line y=3x+2

12 次查看(过去 30 天)
I am trying to figure out how I can calculate the shortest distance of any give cordinate point to the line y=3x+2
I have tried using the following code to do this:
x = 0:0.1:100;
y = 3*x + 2;
plot(x,y);
grid on
pt = [5,0]
a = x - y;
b = pt - y;
d = norm(cross(a,b)) / norm(a);
distance = point_to_line(pt,x,y);
This gives me the following error:
pt =
5 0
Matrix dimensions must agree.
Error in eka (line 10)
b = pt - y;
Any help is highly appreciated with this.

采纳的回答

John D'Errico
John D'Errico 2022-1-11
You have done a fair amount.
Surely you could just look online.
On there, you would find a very simple formula to compute the distance from a point (x0,y0), to a line. There the line is assumed to be of the form: a*x + b*y + c == 0. So your line has the form 3*x - y + 2 == 0.
For example, what is the distance to the line from the point (5,6)?
x0 = 5;
y0 = 6;
a = 3;
b = -1;
c = 2;
D = abs(a*x0+ b*y0 + c)/sqrt(a^2 + b^2)
D = 3.4785
  1 个评论
Esa Kesti
Esa Kesti 2022-1-11
Thanks for your help John, I am complete Noob with everything related to Matlab, trying to learn this from online is not the easiest way. People like you make learning this much more understandable.
Took me a while to understand that you solved my issue and I do appreciate it.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2022-1-11
See my attached point-to-line demo.

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by