File Exchange

image thumbnail

Shortest Distance Between Two Lines in N dimensions

version 1.1 (1.96 KB) by

Function calculates shortest distance between two lines presented by two points for each line.



View License

Function uses algorithm from Dan Sunday internet site
L1, L2 includes two points in matrix of 2*n
where n are dimensions (3 in 3D).
d - shortest distance between two lines
Pc,Qc - points where exists shortest distance d

[d Pc Qc]=distBW2lines(L1,L2)

Functions of lines L1,L2 and shortest distance line
can be plotted in 3d or with minor change in 2D by
removing comments sign from code at the end of the file.
In some cases points Pc,Qc will not displayed accurately on line.
Just change value of par parameter according to point.

Programmed by Alexander Brodsky
newshurik at

Comments and Ratings (3)


Steve (view profile)

Works fine, thanks!

Thanks Guy. I corrected the mistake and made some changes for better running. The main of them is the change of the dot function to matrix multiplication. Dot function takes relatively long time. It was checked in the Profiler.


Guy (view profile)

There is a bug in the code which determines the points along each line where the point of closest approach exists. This is because the distance between the lines uses the variable 'd'. But 'd' is previously set to 'd=dot(u,w0)', and is then needed to calculate 'sc' and 'tc'. So now 'sc' and 'tc' (which calculate 'Pc' and 'Qc') are using the wrong 'd'. This bug is simply fixed by moving the lines calculating 'sc' and 'tc' up a couple lines so they're above the overwriting of 'd'.

This bug is visually VERY obvious if you execute the commented plot script. Also can be verified by checking the length of Pc-Qc compared to the solution for d.



1. Distance value was corrected (thanks to Guy)
2. Dot function was changed by matrix multiplication for speeding the script

MATLAB Release
MATLAB 7.10 (R2010a)

Inspired: Shortest distance between two line segments

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video