Matlab - Curve Fitting Data using lsqcurvefit
07 Dec 2007 Quan Quach 29 comments 14,282 views
Example 1: Continued
-
Use this code to generate the sample data. You can insert it directly into the command prompt window.
%x data x = 0:0.1:5-0.1; %y data %the rand command is used here to introduce some error into %the output because real data is never perfect y = -x.^3 +5.*x.^2+x-15 + rand([1,50])/2; %plot the data as a scatter plot figure scatter(x,y)
-
Next, we need to define the polynomial 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= myPolyCurve (param,input) a = param(1); b = param(2); c= param(3); d= param(4); % this is the 3rd order polynomial equation here output = a.*input.^3 + b.*input.^2 + c.*input.^1 + d;
-
Now we are ready to 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 = [-10 5 10 -15]; %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(@myPolyCurve, initialConditions,x,y);
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 a,b,c, and d. Use the following code to see how the curve fits the data:
figure scatter(x,y) %plot the scatter plot hold %hold the figure %use new parameters to get new output values y2 = myPolyCurve(newParameters,x); %plot the new data using the color red plot(x,y2,'r')
Looks like it was a decent fit.

-
But can we make it fit even better? We sure can. We can include a lower bound, upper bound, and even change the optimization configuration to get a better fit. Of course, doing so will probably require more computing resources, so there is a tradeoff. So if you find that your data isn’t fitting as well as you thought it would, you can try changing some settings to see if it helps. So lets give that a try. Enter these lines of code into the command prompt:
%configure the optimset for use with lsqcurvefit options = optimset('lsqcurvefit'); %increase the number of function evaluations for more accuracy options.MaxFunEvals = 500; lb = [ -20 -20 -20 -20]; %define the lower bound ub =[20 20 20 20]; %define the upper bound %re-evaluate the curve fit with new options [newParameters2,error2] = lsqcurvefit(@myPolyCurve, initialConditions,x,y,lb,ub,options); %use new parameters to get new output values y3 = myPolyCurve(newParameters2,x); %%% plot all the data on the same figure %%% figure scatter(x,y) %plot the scatter plot hold %hold the figure %plot the new data using the color red plot(x,y2,'r') %plot the new data using the color green plot(x,y3,'g')
The red curve is from the first attempt, and the green curve is from the second atempt. Just from visual inspection, it looks like the curve fits even better now!

-
Also, if you compare the values for error1 and error2, you will notice that error2 is smaller than error1, which suggests that the second trial will yield a better fit! If you want to see the values for these two variables, you can type
error1anderror2respectively at the command prompt.
And that’s how you use lsqcurvefit to fit your data. This is the end of the first example. Keep reading to see the next example!
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.