[Math] Closest points on two line segments

linear algebraoptimization

I am looking for a general formulation to find the closest points on two line segments.
What I was thinking about is to define our lines as:

$$ P1 + s (P2-P1)$$

$$ Q1 + t (Q2-Q1)$$

Where $P1 , P2, Q1$ and $Q2$ are the beginning and the end points on each segment.

Now we should go through an optimization problem as: $\min f(s,t)$ such that $0<s<1$ and $0<t<1$. Where $f(s,t)$ is the point-to-point distance function.

Is there any straight forward solution?

Best Answer

Since the thing you are minimizing is an everywhere-positive quadratic function of $t$ and $s$, it is convex in each variable. So, we need its critical point, and failing that, something close to it.

The function has a critical point when the vector connecting points on two lines is orthogonal to each line. At this point, the vector $$v = P1 + s(P2-P1) - Q1- t(Q2−Q1)$$ satisfies $$v\perp (P2-P1) \quad \text{ and} \quad v\perp (Q2-Q1)$$ This is a system of two linear equations with two unknowns $s,t$. Having solved it, you may find that either:

  1. Both $t$ and $s$ are between $0$ and $1$. Then they give the minimum
  2. One or both of $t,s$ are outside of the interval $[0,1]$. Then replace the outlying number with the nearest point of the interval $[0,1]$.