Using NonlinearModelFit function with polynomial I have defined - Mathematica Stack Exchange most recent 30 from mathematica.stackexchange.com 2019-09-22T23:42:20Z https://mathematica.stackexchange.com/feeds/question/201946 https://creativecommons.org/licenses/by-sa/4.0/rdf https://mathematica.stackexchange.com/q/201946 0 Using NonlinearModelFit function with polynomial I have defined Carrson Baldwin https://mathematica.stackexchange.com/users/66528 2019-07-11T19:27:03Z 2019-07-12T05:47:51Z <p>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 <code>NonlinearModelFit</code> function to solve for the coefficients that I have set in my polynomial definition?</p> <pre><code>data = {{1, 1.1}, {2, 3.9}, {4, 15.7}, {5, 26}} polynomial[vars_List, n_Integer, coeff_] := #.Array[coeff, Length@#] &amp;@ DeleteDuplicates[Times @@@ Tuples[Prepend[vars, 1], n]] (* credit to user 'March' *) </code></pre> <p>So the input:</p> <pre><code>polynomial[{x}, 2, a] </code></pre> <p>Gives </p> <pre><code>a + x a + x^2 a </code></pre> <p>To get a fit as a quadratic I want to put in:</p> <pre><code>NonlinearModelFit[data, polynomial[{x}, 2, a], {a}, x] </code></pre> <p>Yet this gives an error. What should I put instead of <code>{a}</code> in the coefficient argument of the <code>NonlinearModelFit</code> function?</p> https://mathematica.stackexchange.com/questions/201946/-/201950#201950 1 Answer by Josh Bishop for Using NonlinearModelFit function with polynomial I have defined Josh Bishop https://mathematica.stackexchange.com/users/42190 2019-07-11T20:31:32Z 2019-07-11T20:31:32Z <p>The list of parameters <code>{a}</code> is just one parameter, and is different from list of the parameters contained in your polynomial, which in the case of your example is <code>{a, a, a}</code>.</p> <p>So the correct syntax for your example would be</p> <pre><code>NonlinearModelFit[data, polynomial[{x}, 2, a], {a, a, a}, x] </code></pre> <p>and you could generate the parameter list programmatically from a polynomial through</p> <pre><code>Cases[polynomial[{x}, 2, a], a[_], \[Infinity]] </code></pre> <p>or similar.</p>