插值
更新中
拟合
原理以及拟合工具箱使用参考:(30条消息) 最小二乘法函数拟合原理及matlab实现—数学笔记_DJZYCDJ的博客-CSDN博客_matlab最小二乘拟合
最小二乘法拟合
原理
多项式的最小二乘法拟合
https://mp.weixin.qq.com/s/A7bbGF
https://mp.weixin.qq.com/s/WO-giI60yUEkSgiRTD7L6A
特殊:直线的最小二乘法拟合
一般情况下的最小二乘法拟合(*)
matlab拟合工具箱
多项式拟合函数:
p = ployfit(x, y, n); % 拟合n次多项式,返回多项式系数矩阵
y = polyval(p, x) % 根据系数矩阵计算x处对应y的值
% 拟合sinx
x = 1:0.1:10;
y = sin(x);
figure(1);
plot(x,y,'Color',[246/255 83/255 20/255],'LineWidth',2);
hold on;
p = polyfit(x,y,5)
plot(x,polyval(p,x),'Color',[124/255 187/255 0/255],'LineWidth',2);
p = 1×6
0.0025 -0.0805 0.9110 -4.4167 8.4704 -4.3302
可以拟合线性或非线性一元和二元函数的组合:fit+fittype:
type = fittype(字符串表达式, name, value); % 字符串表达式说明的是要拟合的函数类型。键值对要指出自变量和因变量
type = fittype(匿名函数, name, value);
fitobj = fit(x, y, type, name, value); % name,value中一般需要设置迭代起始点
fitobj = fit([x,y], z, type, name, value); % x,y,z都是列向量
[fitobj, gof] = fit([x,y], z, type, name, value); % gof包含了一些检验统计量
% 司守奎例5.14
x = linspace(1,10,20);
y = linspace(3,20,20);
z = 1 + 2*log(x) + 3*y;
type = fittype('a + b*log(x) + c*y','dependent',{'z'},'independent',{'x','y'});
[fitobject, gof] = fit([x',y'],z',type,'StartPoint',rand(1,3));
fitobject,gof
General model:
fitobject(x,y) = a + b*log(x) + c*y
Coefficients (with 95% confidence bounds):
a = 1 (1, 1)
b = 2 (2, 2)
c = 3 (3, 3)
gof = 包含以下字段的 struct:
sse: 1.1265e-27
rsquare: 1
dfe: 17
adjrsquare: 1
rmse: 8.1403e-15
可以非线性拟合多个自变量的函数 lsqcurvefit:
arg = lsqcurvefit(func, arg0, x, y, lb, ub, opts);
% arg: 返回的参数向量
% func: 带参数的拟合目标函数
% arg0: 参数的迭代初始值
% x:自变量矩阵,按列排成一个矩阵,每列都是一个自变量对应的值
% y:因变量矩阵(列向量)
% lb,ub: 参数的上下界,自己赋一个值
% opts:一些选项
% 司守奎例5.18
a = readmatrix('数学建模算法与应用(第3版)程序及数据\05第5章 插值与拟合\data5_18.txt');
y = a(:,[2,7]);
y = y(~isnan(y));
x = [a(:,[3:5]);a(1:end-1,[8:10])];
func = @(c,x) exp(-c(1)*x(:,1)).*sin(c(2)*x(:,2))+x(:,3).^2;
lb = zeros(1,2);
ub = ones(1,2);
arg = lsqcurvefit(func,rand(1,2),x,y,lb,ub)
Local minimum possible.
lsqcurvefit stopped because the size of the current step is less than
the value of the step size tolerance.
<stopping criteria details>
arg = 1×2
0.0000 0.3099