1.函数介绍
lsqnonlin 解决非线性最小二乘(非线性数据拟合)问题。
语法:
x = lsqnonlin(fun,x0)
x = lsqnonlin(fun,x0,lb,ub) #lb ≤ x ≤ ub
x = lsqnonlin(fun,x0,lb,ub,options)
x = lsqnonlin(problem)
[x,resnorm] = lsqnonlin(___)
[x,resnorm,residual,exitflag,output] = lsqnonlin(___)
[x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqnonlin(___)
2.部分参数
-
options — Optimization options
MaxFunctionEvaluations:最大函数求值次数,默认值是100*numberOfVariables。
MaxIterations:最大迭代次数,默认值是400次。 -
resnorm — Squared norm of the residual
Squared norm of the residual, returned as a nonnegative real. resnorm is the squared 2-norm of the residual at x: sum(fun(x).^2).
返回残差平方。 -
residual — Value of objective function at solution
目标函数在解处的值,作为数组返回。通常,residual = fun(x)。
3.lsqnonlin与lsqcurvefit区别:
- lsqnonlin: Solve nonlinear least-squares (nonlinear data-fitting) problem(非线性最小二乘);
- lsqcurvefit: Solve nonlinear curve-fitting (data-fitting) problems in least-squares sense(非线性曲线拟合)。
相同点:两者默认算法都是:trust-region-reflective,并且都可以修改为:levenberg-marquardt algorithm
;
如:options = optimoptions(@lsqnonlin,'Algorithm','trust-region-reflective');
可以修改算法为levenberg-marquardt:
options.Algorithm = 'levenberg-marquardt';
[x,resnorm,residual,exitflag,output] = lsqnonlin(fun,x0,[],[],options);
lsqcurvefit 函数使用与 lsqnonlin 相同的算法。lsqcurvefit 只是为数据拟合问题提供一个方便的接口。
不同点:
(1)lsqcurvefit 的使用形式要更简单一点:The lsqcurvefit function uses the same algorithm as lsqnonlin. lsqcurvefit simply provides a convenient interface for data-fitting problems
(2)lsqnonlin函数定义为差值函数,如:fun = @(r)exp(-d*r)-y;
lsqcurvefit 函数定义为目标函数,如:fun = @(x,xdata)x(1)*exp(x(2)*xdata);
4.使用方法
方法一:创建函数文件和求解文件
function F = myfun(x)
F = ... % Compute function values at x
x = lsqnonlin(@myfun,x0)
方法二:不需要单独函数文件
x = lsqnonlin(@(x)sin(x.*x),x0);
注意:
5.实例
t = linspace(0.1, 300, 1000)';
y = 300*exp(-t/5) + 10;
y_noise = y + 20*randn(1000, 1);
% funl = @(p,x,y_noise) p(1)*exp(-x/p(2)) + p(3)- y_noise;
fun = @(x)x(1)*exp(-t/x(2))+x(3) - y_noise;
x0 = [100, 2 1];
options.Algorithm = 'levenberg-marquardt';
[x,resnorm,residual] = lsqnonlin(fun,x0,[],[],options)
plot(t,y_noise,'ro',t,fun(x)+y_noise,'b-')
xlabel('t')
legend('Normal density','Fitted function')
结果:
6.组合多个目标函数的lsqnonlin
https://www.mathworks.com/matlabcentral/answers/285211-how-to-combine-multiple-objective-functions-for-lsqnonlin
function [ rssOutput ] = objFunctions( params,X,Y)
a = params(1); % parameter 1
b = params(2); % parameter 2
rss1 = a.*exp(b.*X) - Y; % objective function 1
rss2 = a.*sin(b.*X) - Y; % objective function 2
rssOutput = [rss1; rss2];
end
x0 = [1,1]'; % initial value of a and b
x=lsqnonlin(@objFunctions,x0,[],[],[],X,Y);
参考资料:
lsqnonlin 函数官网:https://www.mathworks.com/help/optim/ug/lsqnonlin.html
MATLAB文档 lsqnonlin 函数:https://blog.csdn.net/qq_34122861/article/details/103514923
MATLAB 非线性最小二乘拟合 lsqnonline 和 lsqcurvefit(总结很好):https://www.cnblogs.com/pupilLZT/p/13379691.html?ivk_sa=1024320u
MATLAB帮助文档非常有用!