What's the algorithm for computing a least squares plane in (x, y, z) space, given a set of 3D data points? In other words, if I had a bunch of points like (1, 2, 3), (4, 5, 6), (7, 8, 9), etc., how would one go about calculating the best fit plane f(x, y) = ax + by + c? What's the algorithm for getting a, b, and c out of a set of 3D points?
The document Least-Squares Fitting of Segments by Line or Plane describes a least-squares algorithm where the input is a set of line segments rather than a set of points. The output is a line (segments in n dimensions) or a plane (segments in 3 dimensions) or a hyperplane (segments in n dimensions).
There is then a normalization step to give the equation of the plane in the form Ax + By + Cz = D as required. The equation of best fit is then used to give the distance, Δ, of each heavy atom from the plane, where (4)and Ax + By + Cz + D = 0 is the equation of the plane.
A method is developed for fitting a hyperplane to a set of data by least-squares, allowing for independent uncertainties in all coordinates of each data point, and including an error analysis.
Given the equation of a plane as z = a*x + b*y + c, planefit, executed as C = planefit(x,y,z), solves for the coeficients C = [a b c]. Planefit does nothing fancy, it simply sets up and lets MATLAB solve the least-squares problem to solve for the coefficients - a handy utility function.
If you have n data points (x[i], y[i], z[i]), compute the 3x3 symmetric matrix A whose entries are:
sum_i x[i]*x[i], sum_i x[i]*y[i], sum_i x[i] sum_i x[i]*y[i], sum_i y[i]*y[i], sum_i y[i] sum_i x[i], sum_i y[i], n
Also compute the 3 element vector b:
{sum_i x[i]*z[i], sum_i y[i]*z[i], sum_i z[i]}
Then solve Ax = b for the given A and b. The three components of the solution vector are the coefficients to the least-square fit plane {a,b,c}.
Note that this is the "ordinary least squares" fit, which is appropriate only when z is expected to be a linear function of x and y. If you are looking more generally for a "best fit plane" in 3-space, you may want to learn about "geometric" least squares.
Note also that this will fail if your points are in a line, as your example points are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With