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]


a[1] + x a[2] + x^2 a[3]

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?

  • 4
    $\begingroup$ 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]? $\endgroup$
    – JimB
    Jul 11, 2019 at 19:37

1 Answer 1


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[1], a[2], a[3]}.

So the correct syntax for your example would be

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

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

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

or similar.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.