Here it is explained how to do a non linear model fit of data with measurement errors on y axis.
Is there a way to do a non linear fit of data including errors on the x axis? i.e. How to include errors on x axis data in NonLinearModelFit?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityHere it is explained how to do a non linear model fit of data with measurement errors on y axis.
Is there a way to do a non linear fit of data including errors on the x axis? i.e. How to include errors on x axis data in NonLinearModelFit?
So, like J.M pointed out in the comments there is no possible solution when you have BOTH x and y errors. BUT you can sometimes do something if you have x errors but negligible y errors. You just parameterize from $y(x)$ to $x(y)$ and fit it that way with your normal weights.
I made an example for you:
We make a fit for the function $y(x)=a\exp\left(b\cdot x\right)$
Lets make some random points:
function = a*Exp[b*x];
range = {{0, 1}, {0, 6}};
n = 30;
xErrors = RandomVariate[NormalDistribution[0, 0.1], n];
data = Table[{i/n + RandomReal[{-1, 1}]*xErrors[[i]],
function /. {x -> (i/n), a -> 2, b -> 1}}, {i, 1, n}];
(*create random data*)
Now we solve for $x(y)$
sol = (x /.
Refine[Solve[function == y, x, Reals],
a > 0 && y > 0]); (*solve the function for y*)
$=\log(y/a)/b$
We reorder our data from $(x,y)$ to $(y,x)$ and do the weighted fits with instrumental-weights: $p_i=\delta_i^{-2}$
subData = Reverse /@ data; (*remap our data (x,y)\[Rule](y,x)*)
subFit = NonlinearModelFit[subData, Re@sol, {a, b}, y,
Weights -> 1/xErrors^2]; (*fit for x(y)*)
In the end we can plot this with and without weighted fits:
Legended[Show[
ListPlot[data],
Plot[
{Evaluate@(NonlinearModelFit[data, function, {a, b}, x][
"BestFit"]), (*fit unweighted with y(x)*)
function /.
subFit["BestFitParameters"]}, (*use parameterized fit from x(y)*)
{x, range[[1, 1]], range[[1, 2]]}, PlotStyle -> {Red, Blue}],
PlotRange -> range]
, LineLegend[{Red, Blue}, {"unweighted", "weighted"}]]
which gives us the graph:
NonlinearModelFit[]
. $\endgroup$