I am trying to fit a sphere to a set of 3d points by using the method I found here: https://jekel.me/2015/Least-Squares-Sphere-Fit.
I do understand why and how the input matrix and vector are formed, but I have not understood the least squares method itself completely. (I was hoping to skip that since I only need the result). I have gotten this far:
// simplified example: Expected result: R=1000.0, C=(0, 1000, 0)
points = new Vector<double>[]
{
DenseVector.OfArray(new double[] {0.0, 0.0, 0.0, 1.0}),
DenseVector.OfArray(new double[] {0.0, 1000.0, 1000.0, 1.0}),
DenseVector.OfArray(new double[] {1000.0, 1000.0, 0.0, 1.0}),
DenseVector.OfArray(new double[] {0.0, 1000.0, -1000.0, 1.0}),
};
Matrix<double> A = DenseMatrix.OfRowVectors(points);
Vector<double> f = DenseVector.Create(A.RowCount, 0.0);
foreach (var tuple in A.EnumerateRowsIndexed())
{
var index = tuple.Item1;
var row = tuple.Item2;
// Assemble the A matrix
row[0] *= 2.0;
row[1] *= 2.0;
row[2] *= 2.0;
row[3] = 1;
A.SetRow(index, row);
// Assemble the f matrix
f[index] = row[0] * row[0] + row[1] * row[1] + row[2] * row[2];
}
var C = MultipleRegression.NormalEquations(A, f);
// solve for the radius
double t = (C[0] * C[0]) + (C[1] * C[1]) + (C[2] * C[2]) + C[3];
double radius = System.Math.Sqrt(t);
// Actual result: R=4000, C=(0, 4000, 0)
Unfortunately, the results are incorrect. I noticed that the regression examples in the math.net documentation seam to only treat curves. Did I make a mistake or is the library not suited for this kind of problem?