matlab的线性拟合工具箱cftool可以很方便的进行曲线的拟合,但如果想实现m文件调用就可以用下面的方法:
%%
clc
clear
close all
%%
% 构造原始数据
x=0:0.02*pi:2*pi;
s=2*sin(3*x+pi/6)+0.7;
plot(x,s),hold on
sr=s+rand(size(s))*0.5;
plot(x,sr,'r--')
%%
% 利用曲线拟合工具箱函数拟合
ft=fittype('A*sin(w*x+f)+c','coefficients',{'A' 'w'
'f' 'c'},'independent','x')
ftop=fitoptions('Method','NonlinearLeastSquares','StartPoint',[2 3
pi/2 1])
[fr,gof,output]=fit(x',sr',ft,ftop)
covalue = coeffvalues(fr)
%%
% 据拟合的参数绘图
sp=covalue(1)*sin(covalue(2)*x+covalue(3))+covalue(4);
plot(x,sp,'g')
legend('precise','interferred','fitresult')
hold off
ft =
General model:
ft(A,w,f,c,x) = A*sin(w*x+f)+c
ftop =
Normalize: 'off'
Exclude: []
Weights: []
Method: 'NonlinearLeastSquares'
Robust: 'Off'
StartPoint: [2 3 1.570796326794897 1]
Lower: [1x0 double]
Upper: [1x0 double]
Algorithm: 'Trust-Region'
DiffMinChange: 1.000000000000000e-008
DiffMaxChange: 0.100000000000000
Display:
'Notify'
MaxFunEvals: 600
MaxIter: 400
TolFun: 1.000000000000000e-006
TolX: 1.000000000000000e-006
fr =
General model:
fr(x) = A*sin(w*x+f)+c
Coefficients (with 95% confidence bounds):
A
= 2.042 (2.003, 2.08)
w
= 2.999 (2.989, 3.01)
f
= 0.5076 (0.4692, 0.546)
c
= 0.9349 (0.9076, 0.9622)
gof =
sse: 1.827767116564399
rsquare: 0.991349326687698
dfe: 97
adjrsquare:
0.991081780090411
rmse: 0.137269661486366
output =
numobs: 101
numparam: 4
residuals: [101x1 double]
Jacobian: [101x4 double]
exitflag: 1
iterations: 6
funcCount: 31
firstorderopt: 2.542006973738076e-005
algorithm: 'Trust-Region Reflective Newton'
covalue =
2.041908361419719 2.999482129378448 0.507597727761528 0.934900585186387
参考网站: