# Circle least squares fit for 3D data

59 views (last 30 days)
Ciara Gibbs on 7 Aug 2019
Commented: Martin Fuchs on 24 Sep 2020
Hi everyone,
I have 6000 x coordinates, y coordinates and z cooridinates that form a circle that does not perfectly occupy one plane. I am looking to fit the data with a circle but I can only find functions online that do it for x and y coordinates and not including z. I would appreciate any help in creating some code for this as I am not sure where to start (I am a beginner in MATLAB!)
Ciara
Ciara Gibbs on 7 Aug 2019
@Torsten, thank you for the links I will give them a read!

Bruno Luong on 7 Aug 2019
Edited: Bruno Luong on 7 Aug 2019 XC = mean(X,1);
Y=X-XC;
[~,~,V]=svd(Y,0);
Q = V(:,[1 2]); % basis of the plane
Y=Y*Q;
xc=Y(:,1);
yc=Y(:,2);
M=[xc.^2+yc.^2,-2*xc,-2*yc];
% Fit ellipse through (xc,yc)
P = M\ones(size(xc));
a=P(1);
P = P/a;
xyzc = XC' + Q*P(2:3); % center
theta = linspace(0,2*pi);
c = xyzc + r*Q*[cos(theta); sin(theta)]; % fit circle
close all
plot3(X(:,1),X(:,2),X(:,3),'.');
hold on
plot3(c(1,:),c(2,:),c(3,:),'r','LineWidth', 2);
axis equal
Martin Fuchs on 24 Sep 2020
This script is just brilliant!