Functionalize fit

Simple question, suppose I want to fit data and use

Fit[data, {x^4, x^3, x^2, x, 1}, x]


I want to convert the output of fit into a function I can later use. However, I can't put fit[x]:= before the previous code since it just overwrites the value of x in the Fit. How do I do this?

• Probably was asked before but can't find it: fit[x_]:=Evaluate @ Fit[... – Kuba Sep 17 '18 at 15:59

So, two easy ways to handle this. One involves manipulating the order of evaluation, and the other involves using a fitting function that returns a functional object.

First:

f[x_] := Evaluate[Fit[data, {x^4, x^3, x^2, x, 1}, x]];


This evaluates the Fit before setting f[x_]:= to it.

Secondly:

f = LinearModelFit[data, {x^4, x^3, x^2, x}, x]


LinearModelFit returns a model object, which can be called as a function, but has a bunch of other useful properties such as R-squared values and an ANOVA table. These can be examined by calling f["Properties"] and the various labels that shows, such as f["RSquared"]. Note that LinearModelFit, by default, includes a constant term automatically. This can be disabled by setting IncludeConstantBasis -> False.

You may also be interested in knowing that NonlinearModelFit exists and has similar properties, if you end up having to deal with more complicated models.

It has also been pointed out by @HenrikSchumacher and @SjoerdSmit that this is a case where using Set instead of SetDelayed to define the function has the expected and desired result:

f[x_] = Fit[data, {x^4, x^3, x^2, x, 1}, x];


This is actually functionally the same as using Evaluate in the SetDelayed expression. I'd recommend checking this answer for further reading regarding := and =.

• I like the second option better, thank you. – Giovanni Baez Sep 17 '18 at 16:57
• Should be also possible: f[x_] = Fit[data, {x^4, x^3, x^2, x, 1}, x]; – Henrik Schumacher Sep 17 '18 at 17:26
• @HenrikSchumacher: exactly. This is basically the only time you ever use regular Set (= instead of :=) to define a function. – Sjoerd Smit Sep 18 '18 at 8:27
• I was hesitant to edit in an answer that involved f[x_] =, since 4 of the most upvoted posts involving Set vs. SetDelayed seem to be from "common pitfalls for new users", but I couldn't find any particular reasoning to recommend against it after looking, so I've added it here. Thanks. – eyorble Sep 18 '18 at 11:24
• really concise and useful answer; kudos – user42582 Sep 18 '18 at 14:34