Shortest distance between two line segments

Version (2.8 KB) by Nick
Function computes the shortest distance between two line segments.
Updated 4 Jun 2014

View License

Computes the shortest distance between two line segments given start and end points for each. Adapts the algorithm found on Dan Sunday's website (
Usage: Input the start and end x,y,z coordinates for two line segments.
p1, p2 are [x,y,z] coordinates of first line segment and p3,p4 are for
second line segment.

Output: scalar minimum distance between the two segments.

P1 = [0 0 0]; P2 = [1 0 0];
P3 = [0 1 0]; P4 = [1 1 0];
dist = DistBetween2Segment(P1, P2, P3, P4)
dist =


Cite As

Nick (2024). Shortest distance between two line segments (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2010a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes

I have updated the function to now give a variety of outputs. The default output is still the distance, however you can also output the vector connecting the two closest points and the coordinates of those points on the lines.