I need to fit many parameters to several data sets, where a few parameters are common to all data sets. I could do it in two steps, but it is better to perform the fit in a single step, since NonlinearModelFit
cannot deal with the covariance matrix that would be required in the second step. A similar question was asked by April 13, 2016 – List argument for NonlinearModelFit, but somehow it didn't work for me. Boiling this problem to the minimal code, my function and example data could be
f[a_, b_][i_, x_] := a + b[[i]] x
data = Flatten[ Table[
{i,xd,RandomVariate[NormalDistribution[f[1.5, {-0.8, 1.2}][i, xd],0.5]]},
{i,2}, {xd, 3}] , 1]
When I try
fit1 = NonlinearModelFit[data,f[a, {b1, b2}][i, x],
{{a, 1.1}, {b1, 0.6}, {b2, 2.2}}, {i, x}]
NonlinearModelFit
complains that "the expression i cannot be used as a part specification" and other similar warnings many times, but finds the correct result, as well as
fit2 = NonlinearModelFit[data, f[a, b][i, x], {{a, 1.1}, {b, {0.6, 2.2}}}, {i, x}]
However, fit1["ParameterTable"]
gives the correct table, but not fit2["ParameterTable"]
– the list of complaints is varied.
I tried to define an adapter function that takes only scalar parameters that are caught in a List
, which is then forwarded to function f[][]
inside a Module[]
, but the complaints from NonlinearModelFit
are very similar. Taking out the SubValues
from the function definition didn't change anything.
Even if the results are correct, I'm afraid of extending this method to a large problem, truly nonlinear, without understanding what is wrong or what I'm missing.
NonlinearModelFit
is that you have to be able (not just willing) to assume that the error variances are identical (or of a known ratio to each other) for each curve to be fit. $\endgroup$