# Using NonlinearModelFit function with polynomial I have defined

I have a data set that I wish to write a loop for to fit polynomials to. I want to be able to type in the max order polynomial I want it to calculate the fit for and have it solve each along the way. I will worry about the loop part later, for now the question is how do I set the coefficients in the NonlinearModelFit function to solve for the coefficients that I have set in my polynomial definition?

data = {{1, 1.1}, {2, 3.9}, {4, 15.7}, {5, 26}}

polynomial[vars_List, n_Integer, coeff_] :=
#.Array[coeff, Length@#] &@
DeleteDuplicates[Times @@@ Tuples[Prepend[vars, 1], n]]
(* credit to  user 'March' *)


So the input:

polynomial[{x}, 2, a]


Gives

a + x a + x^2 a


To get a fit as a quadratic I want to put in:

NonlinearModelFit[data, polynomial[{x}, 2, a], {a}, x]


Yet this gives an error. What should I put instead of {a} in the coefficient argument of the NonlinearModelFit function?

• Polynomial models are linear models so one doesn't have to use NonlinearModelFit. For a cubic why not use LinearModelFit[data, Table[x^i, {i, 3}], x]? – JimB Jul 11 '19 at 19:37

The list of parameters {a} is just one parameter, and is different from list of the parameters contained in your polynomial, which in the case of your example is {a, a, a}.

So the correct syntax for your example would be

NonlinearModelFit[data, polynomial[{x}, 2, a], {a, a, a}, x]


and you could generate the parameter list programmatically from a polynomial through

Cases[polynomial[{x}, 2, a], a[_], \[Infinity]]


or similar.