Clear Filters
Clear Filters

3D line of best fit

9 views (last 30 days)
kanai
kanai on 7 Jun 2013
Commented: Matt J on 5 Oct 2020
I have about 50000 points with x,y,z data spread in 3 coloumns in excel. I have managed to create a plane of best fit. (by creating a comma delimited file, importing it, setting each column as a variable, then using the SFTOOL function. This gives me a plane of best fit through the data when I select the plane to be polynomial with degrees x=1 and y=1).
What I cannot seem to do is create a line of best fit through this data. This line must be a straight line and I would like to know the parametric equation of this line.
I would be most grateful if someone could advise me (a complete matlab beginner) how to go about this.
Many thanks
regards
kanai

Accepted Answer

Matt J
Matt J on 7 Jun 2013
Suppose the rows of xyz are your data points,
r0=mean(xyz);
xyz=bsxfun(@minus,xyz,r0);
[~,~,V]=svd(xyz,0);
The parametric equation is
r(t) = r0 + t*V(:,1);
  31 Comments
Songqiu
Songqiu on 2 Oct 2020
Hi, Matt,
Thank you very much for your reply.
I have written the following code for calculating the projections of multiple points using a for loop.
Could you please tell me how to avoid using the for loop?
Many thanks.
a = [0, 0, 0];
b = [1, 1, 1];
p = [1, 1, 0];
for i = 2 : 50
p = cat(1, p, [i i 0]);
end
pp = p;
xyz = zeros(size(pp, 1), 3);
for i = 1 : size(pp, 1)
p = pp(i, :);
ap = p-a;
ab = b-a;
xyz(i, :) = a + dot(ap, ab)/dot(ab, ab) * ab;
end
Matt J
Matt J on 5 Oct 2020
ab=(b-a)/norm(b-a);
xyz=(pp-a)*ab(:)*ab + a;

Sign in to comment.

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!