Least Squared Spherical Regression
Port of a MATLAB solution in Mathematica.
Clear["Global`*"];
(*Given coordinates*)
data = {{-1.190185, 0.7824033, 0.1691585}, {-1.152931, 0.7811859,
0.1401751}, {-1.110813, 0.775885, 0.1348239}, {-1.078485,
0.772419, 0.1545465}, {-1.101839, 0.7839018,
0.2090827}, {-1.120642, 0.7859643, 0.2231803}, {-1.136541,
0.7895643, 0.2040433}, {-1.135001, 0.7879777,
0.1715891}, {-1.111366, 0.7854245, 0.1738369}, {-1.115193,
0.78763, 0.1931185}, {-1.130671, 0.7892017,
0.1985596}, {-1.132487, 0.7872546, 0.2240417}, {-1.161051,
0.7876478, 0.171136}, {-1.114549, 0.7809206,
0.1476536}, {-1.083838, 0.7764122, 0.1626304}, {-1.06429,
0.769419, 0.2177327}, {-1.142459, 0.7805369,
0.2528498}, {-1.162153, 0.7863876, 0.1668259}};
sphereFit[data_] :=
Module[{A, B, Center, Radius, meanX, meanY,
meanZ},(*Compute the means*)meanX = Mean[data[[All, 1]]];
meanY = Mean[data[[All, 2]]];
meanZ = Mean[data[[All, 3]]];
(*Compute matrix A*)
A = {{Mean[(data[[All, 1]] - meanX)*data[[All, 1]]],
2*Mean[data[[All, 1]]*(data[[All, 2]] - meanY)],
2*Mean[data[[All, 1]]*(data[[All, 3]] - meanZ)]}, {0,
Mean[(data[[All, 2]] - meanY)*data[[All, 2]]],
2*Mean[data[[All, 2]]*(data[[All, 3]] - meanZ)]}, {0, 0,
Mean[(data[[All, 3]] - meanZ)*data[[All, 3]]]}};
A = A + Transpose[A];
(*Compute vector B*)
B = {Mean[(data[[All, 1]]^2 + data[[All, 2]]^2 +
data[[All, 3]]^2)*(data[[All, 1]] - meanX)],
Mean[(data[[All, 1]]^2 + data[[All, 2]]^2 +
data[[All, 3]]^2)*(data[[All, 2]] - meanY)],
Mean[(data[[All, 1]]^2 + data[[All, 2]]^2 +
data[[All, 3]]^2)*(data[[All, 3]] - meanZ)]};
(*Compute the center*)Center = LinearSolve[A, B];
(*Compute the radius*)
Radius = Sqrt[
Mean[Total[(data - ConstantArray[Center, Length[data]])^2, {2}]]];
(*Return center and radius*){Center, Radius}]
{center, radius} = sphereFit[data];
Print["The Least Squares(LR) Sphere:
Center=", center, " Radius=", radius];
(*Visualize data and best fit sphere*)
Show[Graphics3D[{PointSize[0.02], Point[data], Opacity[0.3],
Sphere[center, radius]}], Axes -> True,
AxesLabel -> {"x", "y", "z"}]
