Path: news.mathworks.com!not-for-mail
From: "John D'Errico" <woodchips@rochester.rr.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Intersection of two straight lines in 3D space
Date: Wed, 11 Mar 2009 17:09:02 +0000 (UTC)
Organization: John D'Errico (1-3LEW5R)
Lines: 56
Message-ID: <gp8r7d$13n$1@fred.mathworks.com>
References: <gp8je2$80b$1@fred.mathworks.com>
Reply-To: "John D'Errico" <woodchips@rochester.rr.com>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1236791342 1143 172.30.248.38 (11 Mar 2009 17:09:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 11 Mar 2009 17:09:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869215
Xref: news.mathworks.com comp.soft-sys.matlab:524102

"James " <mmjpjb2@lboro.ac.uk> wrote in message <gp8je2$80b$1@fred.mathworks.com>...
> Hello,
> 
> I've got two lines in 3D space, each represented by two points (of x,y,z coords) such as:
> 
> A1=[0 0 0];
> A2=[5 5 5];
> 
> B1=[0 5 5];
> B2=[5 0 0];
> 
> I would like to be able to calculate the (x,y,z) coordinates at which they intersect. With my own beginners Matlab knowledge and feeble grasp of maths, I have been able to calculate something similar in 2D (by calculating line equations in the form y=mx+c and then solving) but I am stuck at trying to do this in 3D. 
> 
> Any help would be greatly appreciated, this is a real road block in my work and it is slowly driving me potty!

James,

As has been stated, there will generally be no 
solution, since two lines will probably not intersect.

Do you wish to find the point of nearest approach?

The line defined by A1 and A2 is (as a function of a
parameter t)

  A(t) = A1*(1-t) + A2*t = A1 + (A2 - A1)*t

Likewise,

  B(s) = B1 + (B2 - B1)*s

The solution to this is best obtained by linear algebra.
Just minimize the difference A(t) - B(s), taken in each
dimension. Since the A1, A2, B1, B2 vectors are all row
vectors, do this:

  ts = [A2(:) - A1(:),-(B2(:)-B1(:))]\(B1(:) - A1(:))
ts =
          0.5
          0.5

The closest point of approach is at

A1 + (A2 - A1)*ts(1)
ans =
          2.5          2.5          2.5

B1 + (B2 - B1)*ts(2)
ans =
          2.5          2.5          2.5

See that in this case you chose lines that did in
fact intersect, but it works on any pair of lines
in any number of dimensions.

John