Main Content

lsqcurvefit 进行非线性曲线拟合

lsqcurvefit 使您能够轻松地对数据进行参数化非线性函数拟合。您也可以使用 lsqnonlinlsqcurvefit 只是调用 lsqnonlin 进行曲线拟合的便捷方法。

在此示例中,向量 xdata 表示 100 个数据点,向量 ydata 表示相关联的测量值。生成问题的数据。

rng(5489,'twister') % reproducible
xdata = -2*log(rand(100,1));
ydata = (ones(100,1) + .1*randn(100,1)) + (3*ones(100,1)+...
    0.5*randn(100,1)).*exp((-(2*ones(100,1)+...
   .5*randn(100,1))).*xdata);

xdataydata 之间的建模关系是

ydatai=a1+a2exp(-a3xdatai)+εi.

该代码基于 100 个独立样本(服从均值为 2 的指数分布)生成 xdata。该代码使用 a = [1;3;2] 从其定义方程生成 ydata,并通过添加具有标准差 [0.1;0.5;0.5] 的正态偏差进行扰动。

目标是为与数据拟合最佳的模型找到参数 aˆii = 1、2、3。

为了使用 lsqcurvefit 对数据进行参数拟合,您需要定义拟合函数。将拟合函数 predicted 定义为匿名函数。

predicted = @(a,xdata) a(1)*ones(100,1)+a(2)*exp(-a(3)*xdata); 

为了对数据进行模型拟合,lsqcurvefit 需要参数的初始估计值 a0

a0 = [2;2;2];

调用 lsqcurvefit 以找到最佳拟合参数 aˆi

[ahat,resnorm,residual,exitflag,output,lambda,jacobian] =...
   lsqcurvefit(predicted,a0,xdata,ydata);
Local minimum possible.

lsqcurvefit stopped because the final change in the sum of squares relative to 
its initial value is less than the value of the function tolerance.

检查生成的参数。

disp(ahat)
    1.0169
    3.1444
    2.1596

ahat 的拟合值与 a = [1;3;2] 相差不超过 8%。

如果您有 Statistics and Machine Learning Toolbox™ 软件,请使用 nlparci 函数为 ahat 估计值生成置信区间。

另请参阅

| (Statistics and Machine Learning Toolbox)

相关主题