Skip to content

Instantly share code, notes, and snippets.

@JohanLarsson
Last active August 29, 2015 13:57
Show Gist options
  • Save JohanLarsson/9708648 to your computer and use it in GitHub Desktop.
Save JohanLarsson/9708648 to your computer and use it in GitHub Desktop.
public static Vector<double> FitPolynomial(List<Point> data, int polynomialDegree)
{
//http://mathworld.wolfram.com/LeastSquaresFittingPolynomial.html
Matrix<double> vanderMondeMatrix = new DenseMatrix(data.Count(), polynomialDegree + 1);
for (int i = 0; i < data.Count(); i++)
{
var xValue = data[i].X;
for (int j = 0; j < (polynomialDegree + 1); j++)
{
vanderMondeMatrix[i, j] = Math.Pow(xValue, j);
}
}
Vector<double> y = new DenseVector(data.Select(p => p.Y).ToArray());
var coefficients = vanderMondeMatrix.QR().Solve(y);// Solve(y);
return coefficients;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment