The Levenberg-Marquardt curve-fitting method is actually a combination of two minimization methods: the gradient descent method and the Gauss-Newton method.
/* Calculates the value of a polynomial of degree n evaluated at x. The input argument coefficients is a vector of length n+1 whose elements are the coefficients in incremental powers of the polynomial to be evaluated. param: coefficients polynomial coefficients generated by polyfit() function xValues x axis values return: Fitted Y values. */ template<typename T> std::vector<T> polyval(const std::vector<T>& coefficients, const std::vector<T>& xValues) { size_t nCount = xValues.size(); size_t nDegree = coefficients.size(); std::vector<T> yValues(nCount);
for (size_t i = 0; i < nCount; i++) { T yVal = 0; T xPowered = 1; T xVal = xValues[i]; for (size_t j = 0; j < nDegree - 1; j++) { yVal += coefficients[j] * pow(xVal, nDegree - 1 - j); } yValues[i] = yVal + coefficients[nDegree-1]; }