File Exchange

## 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.

Updated

Function uses algorithm from Dan Sunday internet site
http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm#dist3D_Segment_to_Segment
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

EXAMPLE:
L1=rand(2,3);
L2=rand(2,3);
[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 yahoo.com

Steve

### Steve (view profile)

Works fine, thanks!

Alexander Brodsky

### Alexander Brodsky (view profile)

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

### 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.