
3D Best Fit Line
24 views (last 30 days)
Show older comments
Megan Stockdill
on 17 Oct 2018
Commented: Bruno Luong
on 19 Oct 2018
I am looking to create a best fit line through four points with x, y, and z coordinates and then measure the angle of that line with respect to the z-normal vector. I am unable to find any user functions for easily doing this.
I followed the code from another help topic (https://www.mathworks.com/matlabcentral/answers/405461-how-can-i-create-a-linear-line-of-best-fit-for-a-set-of-3-dimensional-coordinates), but the line of best fit does not look right (see attached). Does anyone know what I am doing wrong?
xyz = [Xl_n{1}(:,15:18)]'; %Xl_n is 3d coordinates matrix z = xyz(:,3); r0=mean(xyz); xyz=bsxfun(@minus,xyz,r0); [~,~,V]=svd(xyz,0); x_fit=@(z_fit) r0(1)+(z_fit-r0(3))/V(3,1)*V(1,1); y_fit=@(z_fit) r0(2)+(z_fit-r0(3))/V(3,1)*V(2,1); figure(1),clf(1) plot3(xyz(:,1),xyz(:,2),xyz(:,3),'ro') hold on plot3(x_fit(z_SI),y_fit(z_SI),z,'r')
0 Comments
Accepted Answer
Bruno Luong
on 17 Oct 2018
Edited: Bruno Luong
on 17 Oct 2018
% Fake n-points in R3, n=4 in your case
n = 10;
a = randn(3,1);
b = randn(3,1);
t = rand(1,10);
xyz = a + b.*t;
xyz = xyz + 0.05*randn(size(xyz)); % size 3 x n
% Engine
xyz0 = mean(xyz,2);
A = xyz-xyz0;
[U,S,~] = svd(A);
d = U(:,1);
t = d'*A;
t1 = min(t);
t2 = max(t);
xzyl = xyz0 + [t1,t2].*d; % size 3x2
% Check
x = xyz(1,:);
y = xyz(2,:);
z = xyz(3,:);
xl = xzyl(1,:);
yl = xzyl(2,:);
zl = xzyl(3,:);
close all
hold on
plot3(x,y,z,'o');
plot3(xl,yl,zl,'r');
axis equal

0 Comments
More Answers (1)
Megan Stockdill
on 19 Oct 2018
1 Comment
Bruno Luong
on 19 Oct 2018
xzyl is 3x2 contains coordinates of 2 points of the lines
- xzyl(:,1) is the 3D coordinates of the first point
- xzyl(:,2) is the 3D coordinates of the second point
The line equation (parametric form) is then
xyz(t) = t*xzyl(:,1) + (1-t)*(xzyl(:,2);
where t is a real parameter.
See Also
Categories
Find more on Get Started with Curve Fitting Toolbox 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!