MATLAB: How to make best fitting and extract it as a report

analysisbest_fittinglinepoint_cloudxyz

Hello to everybody, I have a point cloud;with its X,Y,Z coordinates, but it is almost a line.You can assume that it is a pipe line.Firstly, I want to make best fitting because the line has a noise.My question is that how I can do the best fitting? Moreover, I want to extract this fitting line as a report because I ll need it for making accuracy & correctness analysis.Could you help me please?
Thanks a lot in advance.

Best Answer

Let X, Y, Z be your coordinates. Then a line can be defined as
p * X + q * Y + r * Z + t = 0
which can be reordered as
p * X + q * Y + t = -r * Z
or
-p/r * X + -q/r * Y - t/r = Z
We can then do a linear least squared fit on the known X, Y, Z to find the unknown values, by setting it up as
[X,Y,ones] * [-p/r, -q/r, -t/r]' = Z
and so we code:
coeffs = [X(:), Y(:), ones(length(X),1)] \ Z(:);
and then the line is
-coeffs(1) * X + -coeffs(2) * Y + Z + -coeffs(3) = 0
or
Z = coeffs(1) * X + coeffs(2) * Y + coeffs(3)
which leads to
minx = min(X); miny = min(Y); maxx = max(X); maxy = max(Y);
XX = linspace(minx, maxx); YY = linspace(miny,maxy);
ZZ = coeffs(1) * XX + coeffs(2) * YY + coeffs(3);
scatter3(X, Y, Z, 'b');
hold on
plot3(XX, YY, ZZ, 'r');