Matlab - Curve Fitting Data using lsqcurvefit
07 Dec 2007 Quan Quach 29 comments 13,257 views
Example 2: An Asymptotic Function
-
The sample data for this example is shown in the figure below. Once again, the goal is to find the best curve that will fit these points.

-
The data is characterized by the following equation:

A little background information on the equation: this is an equation to describe the behavior of a limiter. A limiter is a circuit that allows signals below a set value to pass unaffected. After this set level has been reached or supassed, the signal becomes saturated.
-
Use the following code to generate the sample data. Paste this code into the command prompt.
p=4; L=2; %this is the input array Vin = 0:0.1:5-.1; %the rand command is used here to introduce some error into %the output because real data is never perfect Vout = Vin.*(1+abs(Vin./L).^p).^(-1/p)+rand([1,50])/100; %plot the data figure scatter(Vin,Vout);
-
Next, we need to define the limiter equation before we can use
lsqcurvefit. Open a new m-file and paste in the following. After pasting in the code, save the m-file and remember which directory you saved it under.function output = limiter(param,input) p = param(1); L = param(2); output = input.*(1+abs(input./L).^p).^(-1/p);
-
Now, we can use the
lsqcurvefitcommand. Remember to set the Matlab current directory to wherever you saved the previous m-file. Cut and paste this code into the command prompt.%the better your initial condition guesses are, the faster %the lsqcurvefit command will converge onto a solution initialConditions = [4,2]; %newParameters is an array containing the optimal values that will %generate a curve that will best fit your data %error is the sum of the error squared. the lower this number is, the better [newParameters,error] = lsqcurvefit(@limiter, initialConditions,Vin,Vout);
You will probably see the following message when you execute these commands, which is normal:
Optimization terminated: first-order optimality less than OPTIONS.TolFun,
and no negative/zero curvature detected in trust region model -
The newParameters variable contains the calculated values for p and L. Use the following code to see how the curve fits the data using these newly calculated parameters:
figure scatter(Vin,Vout) %plot the scatter plot hold %hold the figure %use new parameters to get new output values Vout2 = limiter(newParameters,Vin); %plot the curve using the color red plot(Vin,Vout2,'r')
Looks like it was a pretty good fit!

-
We can try making it a better fit by using the method shown in the previous example. I will leave this up to you to finish. Good luck!
29 Responses to “Matlab - Curve Fitting Data using lsqcurvefit”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


Thank you so much for this page. Its really helped me out!
All the best in the future,
Hong.
Quan,
Thanks a lot for putting this tutorial up. It is very robust in the sense that anybody using it for any kind of fitting is able to benefit from it.
Great job.
-voy
Thanks so much!!!I was looking for an example like that!
;^)
Sara
thanks a lot
it was very helpful
matlab gives the value of a certain parameter
can it tell you the error in this parameter?
hi
I am very grateful to you.
Your example was very helpful for my data fitting
cheers
Giovanni
Hi,
Perhaps some of you will be interested in
“EzyFit - A free curve fitting toolbox for Matlab”,
check http://www.fast.u-psud.fr/ezyfit/
Comments are welcome!
Frederic Moisy
Is it right to use lsqcurve fit for Gaussian equation of the form
a*exp(b-x) + a1*exp(-((x-b1)/c1)^2) + a2*exp(-((x-b2)/c2)^2)
I think the line [newParameters,error] = lsqcurvefit(@myCurve, initialConditions,Vin,Vout);
should actually be [newParameters,error] = lsqcurvefit(@limiter, initialConditions,Vin,Vout);
Darkspirit,
I think you’re right. I have changed the post to reflect thec hange.
Quan
as Stephen said:
matlab gives the value of a certain parameter
can it tell you the error in this parameter?
please email me if you have the answer. thanks a lot!!!
kerry,
it only returns the residual error (that is, the sum of the error squared).
Quan
Thanks so much for the helpful post. Hope all blogs were this useful.
Cheers
Please, dear friends
tell me how to perform parameter estimation in a ode system like this:
dy1/dt = a*y1 - b*y2 + c
dy2/dt = y1*y2 - a
I have both vectors, y1 and y2, how do I find a, b and c. What function should I use.
thank you in advance
Hey thanks a lot for the information but can u tell me what is happening with my code i gave some initial conditions and it isn’t working.
“No improvement in search direction: Terminating.”
i used a 6th order equation for 6th order equation
venkar,
it looks like your initial conditions might be too far off or something is not right with your equation so it is not able to do the curve fit. try adjusting your initial conditions to see if it garners any improvement,
Quan
can i use ”lsqcurvefit” to find the optimal values
for the parameters (tx,ty,sx.sy,θ,v) that appear in the following function:
g(x,y)=(1/(2*pi*sx*sy))*exp(-0.5*[(x'/sx)^2+(y'/sy)^2])*sin(2*pi*v*x’) ,with
x’=cosθ(x-tx)-sinθ(y-ty)
y’=sinθ(x-tx)+cosθ(y-ty) ?
Thanks for your help.
I have the following code as a Function Argument of the lsqcurvefit. In the equation, there is 100.5 which I want to change. I want to supply that value to following function as an input but when I try to do this it gives error inside the lsqcurvefit. Is it possible to do?
Quan,
If x,y and z are known, will lsqcurvefit be able to find the coefficients (a,b,c,d,e,f) for the following 3D surface?
z(x,y) = a*x^2 + b*y^2 + c*xy + d*x + e*y + f
Any help is much appreciated!
-Tom
Great explanation of how to do the curvefit, it really helped me out alot!
Thanks,
Tommy
hi,
thank you it was helpful but i am using the lsqcurvefit but i am getting some errors can i email you my code ?
hi,
thank you it was helpful but i am using the lsqcurvefit but i am getting some errors can i email you my code ? its urgent… :/
how do i find a single maximum and minimum value of the fitted curve?
Thanks a lot for a great explanation. This has helped me out quite a bit.
Is there a way to turn off the output of the message:
?
I’m trying to use lsqcurvefit to loop over several datasets and having the message repeated a few thousand times is not great.
Thanks again for a great post.
Ok, nevermind. I figured out how to use the options.Display option to get it to turn off output. I was just having trouble because I was trying to use
but after reading this in MATLAB help (I must have missed it the first time):
I corrected myself and included empty matrices for lb and ub and it worked.
Thanks again and thanks anyway.
You’re a life saver, bud. Thanks for the well written tutorial!
hello,
i tried the following code:
B = lsqcurvefit(@polsin,A,polang,intensityy,[0 -255 -2*pi],[255 255 2*pi],optimset(’Display’,'off’));
and got this error
??? Error using ==> lsqncommon at 134
Function value and YDATA sizes are incommensurate.
Error in ==> lsqcurvefit at 186
[x,Resnorm,FVAL,EXITFLAG,OUTPUT,LAMBDA,JACOB] = …
Error in ==> newnew at 164
B = lsqcurvefit(@polsin,A,polang,intensityy,[0 -255 -2*pi],[255 255
2*pi],optimset(’Display’,'off’));
bye
Hi,
Great tutorial! Does anybody know of a way of changing the optimisation criteria? as in, instead of the routine solving for the minimum sum of errors squared, solving it for say the relative error?
Thanks!
Hi,
Do you know how to write code for a data set with a curve that goes back on itself? Over time, there is 2 x-points for the same line because it’s like a ‘S’ curve. Any ideas how to take the lower value?
Thanks.