# Distance from point to line [duplicate]

I'm a newbie with Mathematica and I managed to draw a line and a point in 3D on a graph

Q = Graphics3D[Point[{50, 10, 25}]];
line = ParametricPlot3D[{5 + t, 5 + t, 5 + t}, {t, 0, 100}];
Show[Q, line]


not sure if I wrote the parametric line command correctly (I wanted to draw a $P(t) = P + Vt$ parametric line where $P$ is the starting point (5;5;5) and $V$ a unit vector (1;1;1)).

Now I would like to calculate the distance between the point Q and the line. I know how to do this in linear algebra ($d = ||(Q-P)-\frac{(Q-P)\cdot V}{||v||^2} V||$), but I'm unsure on how to do this. Is there a pre-defined function in mathematica to get the distance from a point to a line?

• This answer is related. There is also an implementation of the formula in the question. – Anton Antonov May 6 '16 at 13:16
• Check out RegionDistance – chuy May 6 '16 at 13:23
• You can also write your parametric formula {5, 5, 5} + t {1, 1, 1}. See also this Q&A -- there are many ways to approach this problem, and many functions one might use (Norm, EuclideanDistance, Dot, Projection,...). – Michael E2 May 6 '16 at 13:32

You can use RegionNearest

pt = {50, 10, 25};
line = Line[Table[{5 + t, 5 + t, 5 + t}, {t, 0, 100}]];
npt = RegionNearest[line, pt];
Graphics3D[{line, Blue, Line[{pt, npt}], Red, Point[{pt, npt}]}]


Is there a pre-defined function in Mathematica to get the distance from a point to a line?

There isn't one, but thankfully for you, both EuclideanDistance[] and Projection[] are built-in:

PointLineDistance[pt_, {s1_, s2_}] :=
With[{tp = s1 - pt}, EuclideanDistance[tp, Projection[tp, s2 - s1]]]


Thus,

PointLineDistance[{50, 10, 25}, {{5, 5, 5}, {5, 5, 5} + {1, 1, 1}}]
35 Sqrt[2/3]

p = {50, 10, 25};
l = InfiniteLine[{5, 5, 5}, {1, 1, 1}];

RegionDistance[l, p]