3
$\begingroup$

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?

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

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 =.

$\endgroup$
  • $\begingroup$ I like the second option better, thank you. $\endgroup$ – Giovanni Baez Sep 17 '18 at 16:57
  • 1
    $\begingroup$ Should be also possible: f[x_] = Fit[data, {x^4, x^3, x^2, x, 1}, x]; $\endgroup$ – Henrik Schumacher Sep 17 '18 at 17:26
  • $\begingroup$ @HenrikSchumacher: exactly. This is basically the only time you ever use regular Set (= instead of :=) to define a function. $\endgroup$ – Sjoerd Smit Sep 18 '18 at 8:27
  • $\begingroup$ 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. $\endgroup$ – eyorble Sep 18 '18 at 11:24
  • $\begingroup$ really concise and useful answer; kudos $\endgroup$ – user42582 Sep 18 '18 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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