MATLAB: 3D Best Fit Line

lineMATLAB

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')

Best Answer

% 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