用Matlab做線性擬合方法
- 電腦
- 關注:1.21W次
簡介
(01)非線性最小二乘優化在曲線擬合、參數估計等問題中有着廣泛的應用。例如,我們要擬合一系列觀測數據(t,y),擬合函數為F(t,x),他是x的非線性函數。對於這種最小二乘曲線擬合問題,可以通過Matalb優化工具箱中的lsqcurvefit命令求解,可以根據實際問題進行曲線擬合。
例題
(01)在工程實驗中,測得下面一組數據。求係數a、b、c、d,使得函數為表中數據的最佳擬合函數。f(t)=a+b·sin(t)+c·cos(t)+dt3
觀測數據表
(01)——————————————————————————————————t | 0 0.5 1 1.5 2 2.5 3 3.5 4——————————————————————————————————y | 0 3.4 4.1 4.6 5.9 6.9 8.1 9.8 11——————————————————————————————————
操作方法
(01)首先建立擬合函數M文件如下:
(02)function f=example8_15(x,ti)n=length(ti);for i=1:nf(i)=x(1)+x(2)*sin(ti(i))+x(3)*cos(ti(i))+x(4)*ti(i)^3;end
(03)從命令窗口輸入
(04)>> ti=[0 0.5 1 1.5 2 2.5 3 3.5 4];>> yi=[0 3.4 4.1 4.6 5.9 6.9 8.1 9.8 11];>> x0=[1 1 1 1]x27;; %初始點選為全1向量>> [x,resnorm,residual,exitflag,output,lambda,J]=lsqcurvefit(@example8_15,x0,ti,yi)
(05)輸出結果為
(06)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Optimization completed because the size of the gradient is less thanthe default value of the function tolerance.<stopping criteria details>x =1.87062.7714-1.04770.1708resnorm =2.9080residual =Columns 1 through 70.8228 -1.0989 -0.2927 0.5373 0.2929 0.1372 -0.1897Columns 8 through 9-0.5977 0.3887exitflag =1output =firstorderopt: 6.6428e-08iterations: 2funcCount: 15cgiterations: 0algorithm: 'trust-region-reflective'message: [1x425 char]lambda =lower: [4x1 double]upper: [4x1 double]J =(1,1) 1.0000(2,1) 1.0000(3,1) 1.0000(4,1) 1.0000(5,1) 1.0000(6,1) 1.0000(7,1) 1.0000(8,1) 1.0000(9,1) 1.0000(2,2) 0.4794(3,2) 0.8415(4,2) 0.9975(5,2) 0.9093(6,2) 0.5985(7,2) 0.1411(8,2) -0.3508(9,2) -0.7568(1,3) 1.0000(2,3) 0.8776(3,3) 0.5403(4,3) 0.0707(5,3) -0.4161(6,3) -0.8011(7,3) -0.9900(8,3) -0.9365(9,3) -0.6536(2,4) 0.1250(3,4) 1.0000(4,4) 3.3750(5,4) 8.0000(6,4) 15.6250(7,4) 27.0000(8,4) 42.8750(9,4) 64.0000%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
(07)再在命令窗口中輸入:
(08)>> xi=0:0.1:4;>> y=example8_15(x,xi);>> plot(ti,yi,'r*')>> grid on>> hold on>> plot(xi,y)>> legend('觀測數據點','擬合曲線')>> title('最小二乘曲線擬合')
(09)輸出結果如下圖所示:
- 文章版權屬於文章作者所有,轉載請註明 https://miaozhigu.com/sm/diannao/z171lv.html