7
$\begingroup$

Like the title says, is there a way to make an NLM fit pass through a specific point.

$\endgroup$
4
  • 2
    $\begingroup$ You can add a constraint to your model. $\endgroup$ Nov 13, 2014 at 12:44
  • 1
    $\begingroup$ like what? I've tried specifying a value but it doesn't work. $\endgroup$
    – A. Napster
    Nov 13, 2014 at 13:08
  • $\begingroup$ Or do a weighted fit with a very large weight for your point. $\endgroup$ Nov 13, 2014 at 17:02
  • $\begingroup$ The question is hastily written with not a tremendous amount of thought put in to it; however, I think it is a valid question and worthy of staying open since setting this type of constraint isn't always obvious. $\endgroup$ Nov 13, 2014 at 18:14

1 Answer 1

13
$\begingroup$
data = Table[{i, i}, {i, 10}];
model = a + b x ^2;

Unrestricted model:

nlm = NonlinearModelFit[data, model, {a, b}, x] // Normal 

$ 0.0863422 x^2+2.17582 $

Model restricted to pass through {5,5}:

nlmr = NonlinearModelFit[data, {model, (model /. x -> 5 ) == 5}, {a, b}, x] // Normal

$ 0.0790502 x^2+3.02375 $

Picture:

Show[Plot[{nlm, nlmr}, {x, 1, 10}, PlotStyle -> Thick, PlotLegends -> {"nlm", "nlmr"}],
 ListPlot[Labeled[#, #, Top] & /@ data],
 Graphics[{Red, PointSize[Large], Point[{5, 5}]}]]

enter image description here

You could also do:

model2[x_] := a + b x ^2;
nlm2 = NonlinearModelFit[data, model2[x], {a, b}, x] // Normal 
nlmr2 = NonlinearModelFit[data, {model2[x], model2[5] == 5}, {a, b}, x] // Normal

You can also have multiple constraints, e.g., can force the fit to pass through two points {1,1} and {7,7}:

nlmr2 = NonlinearModelFit[data, 
           {model2[x], model2[1] == 1 && model2[7] == 7}, {a, b}, x] // Normal

Show[Plot[{nlm2, nlmr2}, {x, 1, 10}, PlotStyle -> Thick, PlotLegends -> {"nlm2", "nlmr2"}],
     ListPlot[Labeled[#, #, Top] & /@ data],
     Graphics[{Red, PointSize[Large], Point[{{1, 1}, {7, 7}}]}]]

enter image description here

$\endgroup$
4
  • $\begingroup$ ok thanks. I thought it was model[5]==5 ? $\endgroup$
    – A. Napster
    Nov 13, 2014 at 13:17
  • $\begingroup$ @Dan, thanks for the accept. You can also use that form if you previously defined model as a function (i.e. model[x_]:= ... as opposed to model = ...). $\endgroup$
    – kglr
    Nov 13, 2014 at 13:22
  • $\begingroup$ ok. now it seems a bit clearer. Thanks again $\endgroup$
    – A. Napster
    Nov 13, 2014 at 13:24
  • $\begingroup$ @Dan, my pleasure. $\endgroup$
    – kglr
    Nov 13, 2014 at 13:25

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.