View Source
In the MATLAB optimization toolbox,function lsqnonlin could be used to solve nonlinear least-squares or nonlinear data-fitting problems。The function's invoke format is as follows:
x = lsqnonlin(fun,x0)There is another function lsqcurvefit could also be availabe in solving the nonlinear LS problems or nonlinear data-fitting problems。Lsqcurvefit could be invoked like this:
x = lsqnonlin(fun,x0,lb,ub)
x = lsqnonlin(fun,x0,lb,ub,options)
[x,resnorm] = lsqnonlin(...)
[x,resnorm,residual] = lsqnonlin(...)
[x,resnorm,residual,exitflag] = lsqnonlin(...)
[x,resnorm,residual,exitflag,output] = lsqnonlin(...)
[x,resnorm,residual,exitflag,output,lambda] = lsqnonlin(...)
[x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqnonlin(...)
x = lsqcurvefit(fun,x0,xdata,ydata)And now I will show you an example of non-linear data-fitting problem using both the functions lsqnonlin and lsqcurvefit, and more, I will compare the result in both functions.
x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub)
x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options)
[x,resnorm] = lsqcurvefit(...)
[x,resnorm,residual] = lsqcurvefit(...)
[x,resnorm,residual,exitflag] = lsqcurvefit(...)
[x,resnorm,residual,exitflag,output] = lsqcurvefit(...)
[x,resnorm,residual,exitflag,output,lambda] = lsqcurvefit(...)
[x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(...)
Firstly,plot the given data and determine what kind of nonlinear function could be suitable for fitting the given data.
xdata =[0,4,6,10,12,16,22,26,30];
ydata =[-33.8980,-13.3859,-6.2068,1.9980,3.0236,-1.0788,-22.6163,-47.2308,-80.0499];
plot(xdata,ydata,'bo');
title('original data points');
Lsqnonlin
In order to use the lsqnonlin function to realize the data-fitting, the objective nonlinear fitting function has to be prescribedly established.
function [feval]=curvefit_fun(x,xdata,ydata)And then, enter the follwing commands in the MATLAB commands workspace:
yval=x(1)*(xdata-x(2)).^2+x(3);
feval=yval-ydata;
x0=[0;0;0];The fitting curve is as:
[x,resnorm,residual,exitflag,output] = lsqnonlin(@(x)curvefit_fun(x,xdata,ydata),x0)
x1=linspace(min(xdata),max(xdata),1000);
y1=x(1)*(x1-x(2)).^2+x(3);
hold on
plot(x1,y1,'r-');
legend('数据点','lsqnonlin函数拟和曲线')
Lsqcurvefit
Firstly, the objective fitting curve function should be established. You ought to pay attention to the differences of the two objectives in Lsqnonlin and lsqcurvefit:
And then, enter the following commands in the MATLAB command workspace:
function [feval]=curvefit_fun(x,xdata)
feval=x(1)*(xdata-x(2)).^2+x(3);
The result is:
x0=[0;0;0];
[x,resnorm,residual] = lsqcurvefit(@(x,xdata)curvefit_fun(x,xdata),x0,xdata,ydata)
x1=linspace(min(xdata),max(xdata),1000);
y1=x(1)*(x1-x(2)).^2+x(3);
hold on
plot(x1,y1,'r-')
legend('数据点','lsqcurvefit拟和曲线')
More details could be found in my published book:
MATLAB编程基础与典型应用
北京:人民邮电出版社,2008
ISBN:978-7-115-17932-6/TP
Pls contact me with Email:lhd06@mails.tsinghua.edu.cn
更多MATLAB资源,欢迎交流:
No comments:
Post a Comment