read data and fit a sphere in matlab

Here is one way to read data from a text file and fit a sphere to the points in Matlab:

main.m
% read data from file
data = dlmread('points.txt');

% separate into x, y, and z coordinates
x = data(:, 1);
y = data(:, 2);
z = data(:, 3);

% create design matrix
D = [x.^2 + y.^2 + z.^2, x, y, z, ones(size(x))];

% fit sphere using linear regression (least squares)
[~, ~, V] = svd(D);
c = V(:, end);
radius = sqrt(c(2)^2 + c(3)^2 + c(4)^2 - 4*c(1)*c(5))/(2*abs(c(1)));
center = -c(2:4)/(2*c(1));

% plot sphere and data
[xs, ys, zs] = sphere;
figure;
surf(xs*radius+center(1), ys*radius+center(2), zs*radius+center(3), 'FaceColor', 'blue', 'EdgeColor', 'none');
hold on;
scatter3(x, y, z, 'red');
axis equal;
613 chars
25 lines

Assuming that the coordinates for the points are stored in a text file called "points.txt" with each point on a separate line and the x, y, and z coordinates separated by spaces or tabs, the code reads in the data using dlmread. It then creates a design matrix D by raising the x, y, and z coordinates to the power of 2 and adding a column of ones. The first column of D corresponds to the radius of the sphere, while the second to fourth columns correspond to the x, y, and z coordinates of the center. The last column of D is just for convenience in the linear regression.

The sphere is then fit by performing linear regression on D. The center and radius are calculated from the coefficients of the linear regression using the formulas given in the code, and the sphere and data points are plotted using surf and scatter3, respectively.

gistlibby LogSnag