function [xc, yc, R, residuals] = fitCircleLSQ(x, y)
% This function fits a circle to a set of 2D points using least squares.
% Inputs:
% x - x-coordinates of the points
% y - y-coordinates of the points
% Outputs:
% xc, yc - coordinates of the circle's center
% R - radius of the circle
% residuals - residuals of the fit
% Number of points
n = length(x);
% Formulate the design matrix
A = [2*x, 2*y, ones(n, 1)];
% Formulate the right-hand side vector
b = x.^2 + y.^2;
% Solve the normal equations using least squares
sol = A\b;
% Extract circle parameters from the solution
xc = sol(1);
yc = sol(2);
c = sol(3);
% Calculate the radius
R = sqrt(c + xc^2 + yc^2);
% Calculate residuals
residuals = (sqrt((x - xc).^2 + (y - yc).^2) - R).^2;
% Display results
fprintf('Fitted circle center: (%.4f, %.4f)\n', xc, yc);
fprintf('Fitted circle radius: %.4f\n', R);
end
% Example usage:
% x = [1, 2, 3]; % Replace with your x-coordinates
% y = [4, 5, 6]; % Replace with your y-coordinates
% [xc, yc, R, res] = fitCircleLSQ(x, y);
% Use the example usage part with your own data points to fit a circle.
This code doesn't account for potential numerical issues or outliers, but it's a good starting point for fitting a circle to data using a straightforward least squares approach. Feel free to customize and expand it for more robust applications.