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

9 views (last 30 days)
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.

Accepted Answer

John D'Errico
John D'Errico on 11 Jan 2022
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 Comment
Esa Kesti
Esa Kesti on 11 Jan 2022
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.

Sign in to comment.

More Answers (1)

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

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!