# I know the coordinates of several scattered points in space, how can I fit them to a sphere?

3 views (last 30 days)
Sterne_17 on 4 Feb 2023
Commented: Sterne_17 on 4 Feb 2023
I already know the coordinates (x,y,z) of several scattered points on a sphere in space, and my goal is to fit a sphere and get the radius. I think I just need to bring their coordinates into the code I found. I would like to ask how to bring in the coordinates of these points?
function [r,a,b,c] = sphereFit(data)
xx = data(:,1);
yy = data(:,2);
zz = data(:,3);
AA = [-2*xx, -2*yy , -2*zz , ones(size(xx))];
BB = [ -(xx.^2+yy.^2+zz.^2)];
YY = mldivide(AA,BB); %Trying to solve AA*YY = BB
a = YY(1);
b = YY(2);
c = YY(3);
D = YY(4); % D^2 = a^2 + b^2 + c^2 -r^2(where a,b,c are centers)
r = sqrt((a^2+b^2+c^2)-D);
The second code:
A=[mean(X(:,1).*(X(:,1)-mean(X(:,1)))), ...
2*mean(X(:,1).*(X(:,2)-mean(X(:,2)))), ...
2*mean(X(:,1).*(X(:,3)-mean(X(:,3)))); ...
0, ...
mean(X(:,2).*(X(:,2)-mean(X(:,2)))), ...
2*mean(X(:,2).*(X(:,3)-mean(X(:,3)))); ...
0, ...
0, ...
mean(X(:,3).*(X(:,3)-mean(X(:,3))))];
A=A+A.';
B=[mean((X(:,1).^2+X(:,2).^2+X(:,3).^2).*(X(:,1)-mean(X(:,1))));...
mean((X(:,1).^2+X(:,2).^2+X(:,3).^2).*(X(:,2)-mean(X(:,2))));...
mean((X(:,1).^2+X(:,2).^2+X(:,3).^2).*(X(:,3)-mean(X(:,3))))];
Center=(A\B).';
Which code should I choose and apply correctly?
##### 2 CommentsShowHide 1 older comment
Sterne_17 on 4 Feb 2023

Image Analyst on 4 Feb 2023
Edited: Image Analyst on 4 Feb 2023
It looks like the input data for both functions is an N-by-3 matrix.