MATLAB: How to create a linear line of best fit for a set of 3-dimensional coordinates

line of best fitlinear regressionMATLAB

I have 3 sets of data containing 10 numbers each. example >> x=[-77.0675, -75.3709, -73.4958, -70.8106, -68.0568, -65.7213, -63.6809, -61.8022, -60.7548, -59.0176]; >> y=[-174.3252, -176.0859, -178.0156, -180.2053, -182.2752, -184.0714, -186.6690, -189.5100, -191.8722, -194.4930]; >> z=[738.9531, 736.8734, 735.4359, 735.1597, 735.2994, 735.8879, 736.5197, 737.7522, 738.6343, 739.2247]; I can 3d plot this data with the plot3 command, but am unable to create a linear line of best fit for the 3 data sets. Does anybody know how to do this?

Best Answer

You could do something like the code below, although I doubt that is what you want (the trend looks like a parabola to me), nor can I guarantee this will yield the best linear fit in 3D.
x=[ -77.0675, -75.3709, -73.4958, -70.8106, -68.0568, ...
-65.7213, -63.6809, -61.8022, -60.7548, -59.0176];
y=[-174.3252, -176.0859, -178.0156, -180.2053, -182.2752, ....
-184.0714, -186.6690, -189.5100, -191.8722, -194.4930];
z=[ 738.9531, 736.8734, 735.4359, 735.1597, 735.2994, ...
735.8879, 736.5197, 737.7522, 738.6343, 739.2247];
xyz=[x(:),y(:),z(:)];
r=mean(xyz);
xyz=bsxfun(@minus,xyz,r);
[~,~,V]=svd(xyz,0);
x_fit=@(z_fit) r(1)+(z_fit-r(3))/V(3,1)*V(1,1);
y_fit=@(z_fit) r(2)+(z_fit-r(3))/V(3,1)*V(2,1);
figure(1),clf(1)
plot3(x,y,z,'b')
hold on
plot3(x_fit(z),y_fit(z),z,'r')