# Problems fitting a function with a NonlinearLeastSquares model

4 views (last 30 days)
Luca Amerio on 15 May 2015
Commented: Torsten on 18 May 2015
Hi everybody.
I need to fit some experimental data on the function
y=sqrt(A*((x-x0)/0.04).^-n)
I understand this to be a tricky function, but sadly it's the one that i need to fit. My unknowns are A, x0 and n.
To test the algorithm i prepared a benchmark case where A, x0 and n are know. Sadly the fit does not works (more or less, i'll explain later) not even in this easy way. The script is
%Initial Data
M=0.04;
A=3000;
n=1.3;
x0=1;
%Generate x y coordinates
x=linspace(x0,100*M,1000);
y=sqrt(A*((x-x0)/M).^-n)+0.1*randi([-1 1],size(x));
figure
loglog(x,y)
%Select fit range
minimumFittinX=1.4;
y=y(x>minimumFittinX);
x=x(x>minimumFittinX);
hold on
loglog(x,y)
% %%%%% FIT %%%%%
options=fitoptions('Method','NonlinearLeastSquares');
options.Lower = [500 0 1];
options.StartPoint = [A x0 n]; %NB: I start from the correct value!!!
options.Upper = [10000 .8*min(x) 2.5]; %Limiting max(x0) to .8*min(x) guarantees to be far enough from the x=x0 asymptote and (x-x0) to be always >0
options.MaxIter = 1000;
type=fittype('sqrt(A*((x-x0)/0.04).^-n)');
fittedFun = fit(x',y',type,options); %Fitto
% Results
IFitted = feval(fittedFun,x);
Afit=fittedFun.A;
x0fit=fittedFun.x0;
nfit=fittedFun.n;
plot(x,IFitted)
sprintf('Interpolated using equation y=sqrt(A*((x-x0)/M).^-n) with:\nA\t=\t%f\nx0\t=\t%f\nn\t=\t%f',Afit,x0fit,nfit)
As you can see I define a range to be fitted using minimumFittinX.
For value of minimumFittinX above 1.3 there's no problem. If you set minimumFittinX at 1.2 however, fit returns the error:
Complex value computed by model function, fitting cannot continue.
Try using or tightening upper and lower bounds on coefficients.
Other times it returns
Inf computed by model function, fitting cannot continue.
Try using or tightening upper and lower bounds on coefficients.
Now... using the upper and lower bound I set for the 3 variables the y value should be limited between 0.13 and 57, way far from Inf!! Moreover min(x-x0) = 1.2, therefore where that Complex value comes from??
How can I improve the fit and make it more robust? This is even a case where the starting value where the correct ones. I can't even think about using real experimental data (I tried with obvious results).
Torsten on 18 May 2015
y=sqrt(A^2*(((x-x0)/0.04).^2).^n)
Best wishes
Torsten.

### Categories

Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!