# How can I get a fully functional FittedModel when fitting data to a pointwise function?

When I am fitting data with a pointwise function using NonlinearModelFit, the produced FittedModel fails to calculate variances and errors. Consider a toy example:

Clear[f, data];
data = {{1, 7.4}, {2, 1.9}, {3, 6.}};
f[1.] = 2. a + b;
f[2.] = 3. a/b;
f[3.] = 3. b/a + a;
fit = NonlinearModelFit[data, f[t], {a, b}, t, Method -> NMinimize]


When I take

fit["BestFitParameters"]


it gives a correct result {a -> 2.19044, b -> 2.95013}. However, when I try to take

fit["EstimatedVariance"]


it throws exception, since values of a and b can not be substituted in fit["Function"] (that's my guess).

I found the following obvious workaround:

Clear[f, g, h];
f[1.] = 1; g[1.] = 0; h[1.] = 0;
f[2.] = 0; g[2.] = 1; h[2.] = 0;
f[3.] = 0; g[3.] = 0; h[3.] = 1;
fit =
NonlinearModelFit[data, (2 a + b) f[t] + 3 a/b g[t] + (3 b /a + a) h[t],
{a, b}, t, Method -> NMinimize]


but it is not elegant at all.

What is the best way to obtain a complete FittedModel using NonlinearModelFit with a pointwise functions?

You should redefine the function:

Clear[f, data];
data = {{1, 7.4}, {2, 1.9}, {3, 6.}};
f[1., a_, b_] := 2. a + b;
f[2., a_, b_] := 3. a/b;
f[3., a_, b_] := 3. b/a + a;


Now it does what you want:

In[]:=  fit = NonlinearModelFit[data, f[t, a, b], {a, b}, t, Method -> NMinimize]
Out[]:= FittedModel[f[t,2.1904, 2.95013]]
In[]:=  fit["EstimatedVariance"]
Out[]:= 0.165311


I think you may be overly complicating this problem. Here's a way to find the a and b that minimize your three equations:

FindMinimum[(7.4 - (2. a + b))^2 + (1.9 - (3. a/b))^2 + (6. - (3. b/a + a))^2, {a, b}]


which gives {0.165311, {a -> 2.19044, b -> 2.95013}}

So now you know the a and b that best fit the data, you can calculate whatever statistics you want from them. In particular, the first term (the error 0.165311) is a measure of how good the functions with the given parameters fit the data. Since I used the squared error, this is much like the variance of the fit.

• Thanks! I'm doing in this way, but I tried to find a way to generate all statistics automatically using NonlinearModelFit. – Stanislav Poslavsky Feb 5 '14 at 17:34