TITLE: Finding the intersection point of many lines in 3D (point closest to all lines)
QUESTION [23 upvotes]: I have many lines (let's say 4) which are supposed to be intersected. (Please consider lines are represented as a pair of points). I want to find the point in space which minimizes the sum of the square distances to all of the lines or in other words, the point which is closest to all the lines.
I want to formulate this as a Least Squares Problem, but I'm not quite sure how it would be. I found the way to compute the distance between line and point. So, I need help to go further.
(As I can't access for optimization packages, I want to implement this with least squares.)

REPLY [6 votes]: In order to find the intersection point of a set of lines, we calculate the point with minimum distance to them. Each line is defined by an origin ${a}_{i}$ and a unit direction vector, ${n}_{i}$. The square of the distance from a point $p$ to one of the lines is given from Pythagoras:  
$$
d_{i}^{2}={{\left[ \left| \left| p-{{a}_{i}} \right| \right| \right]}^{2}}-{{\left[ {{\left( p-{{a}_{i}} \right)}^{T}}*{{n}_{i}} \right]}^{2}}={{\left( p-{{a}_{i}} \right)}^{T}}*\left( p-{{a}_{i}} \right)-{{\left[ {{\left( p-{{a}_{i}} \right)}^{T}}*{{n}_{i}} \right]}^{2}}
$$ 
Where ${\left(p-a_i\right)}^T*n_i$ is the projection of ($p-a_i)$ on the line i. The sum of distances to the square to all lines is: 
$$
\underset{i}{\mathop \sum }\,d_{i}^{2}=\underset{i}{\mathop \sum }\,\left[ {{\left( p-{{a}_{i}} \right)}^{T}}*\left( p-{{a}_{i}} \right)-{{\left[ {{\left( p-{{a}_{i}} \right)}^{T}}*{{n}_{i}} \right]}^{2}} \right]
$$  
To minimize this expression, we differentiate it with respect to $p$.   
$$
\underset{i}{\mathop \sum }\,\left[ 2*\left( p-{{a}_{i}} \right)-2* \right[{{\left( p-{{a}_{i}} \right)}^{T}}*{{n}_{i}}]*{{n}_{i}}]=0
$$
$$
\underset{i}{\mathop \sum }\,\left( p-{{a}_{i}} \right)=\underset{i}{\mathop \sum }\,\left[ {{n}_{i}}*{{n}_{i}}^{T} \right]*\left( p-{{a}_{i}} \right)
$$
It results:  
$$
[\underset{i}{\mathop \sum }\,\left[ {{n}_{i}}*{{n}_{i}}^{T}-I \right]]*p=\underset{i}{\mathop \sum }\,\left[ {{n}_{i}}*{{n}_{i}}^{T}-I \right]*{{a}_{i}}
$$
Where $I$ is the identity matrix. This is a matrix $~S*p=C$, with solution   $p={{S}^{+}}*C$ , ${{S}^{+}}~$, being the pseudo-inverse of $S$. 
Straightforward implementation can be found on: 
http://www.mathworks.com/matlabcentral/fileexchange/37192-intersection-point-of-lines-in-3d-space