-3

Good morning,

so what I have is a bunch of 3D points. Now I just want to fit a line through it without setting one axis to zero!

I could not find anything, can you help me? (If it helps I use Matlab)

Is Ordinary least square fitting an option? I just read about it and do not really now how to use it for a line.

  • Please read on how to ask a [good question](https://stackoverflow.com/help/how-to-ask) and show some effort (not saying that you didn't, but it is not visible here). Search SO. That said, does this [python solution](https://stackoverflow.com/a/51891284/803359) give some insight? – mikuszefski Jul 29 '21 at 08:42

1 Answers1

1

Suppose your points are Q1..Qn. We can define a line by a point P on the line and a unit vector u that points along the line.

In any dimension, we can find the line as below.

Given a point Q the closest point on the line to Q is then

Q^ = P + u'*(Q-P)*u

The squared distance of Q from the line is the distance squared between Q and Q^

dsq = || Q-Q^||^2 = ||(Q-P)||^2 - (u'*(Q-P))^2

One approach to finding the best fit line is to look for the line that minimises the mean squared distances of the points from the line, ie to minimise

E = Sum{ j | ||(Q[j]-P)||^2 - (u'*(Q[j]-P))^2 }/n

Some rather tedious algebra shows that this means that

P = Sum{ j | Q[j]}/n -- ie the mean of the Qs

u the eigenvector of C corresponding to the largest eigenvalue of C, where

C = Sum{ j | (Q[j]-P)*(Q[j]-P)'} -- the covariance of the Qs

So the drill to find P and u is:

Compute P = Sum{ j | Q[j]}/n

Compute C = Sum{ j | (Q[j]-P)*(Q[j]-P)'}

diagonalise C and select u to be the eigenvector corresponding to the largest eigenvalue. Note C is symmetric, so diagonalising should not be a problem.

dmuir
  • 4,211
  • 2
  • 14
  • 12