通過矩陣計算的方式實現用最小二乘法擬合高次函數曲線
matlab源程序如下:
- clc;
- clear;
- close all;
- %% 取樣并代入曲線
- x_all = 0:0.01:1.81;
- [y_truth_all,y_all]=unknown_model1(x_all);
- N = length(x_all);
- %用前半段取樣點訓練并顯示理想值
- x = x_all(1:N/2);
- y = y_all(1:N/2);
- y_truth = y_truth_all(1:N/2);
- plot(x,y_truth,'g-x','LineWidth',1.5);
- hold on;
- plot(x,y,'m-x','LineWidth',1.5);
- legend('model truth','observation');
- title('training');
- %% 二階曲線擬合
- X = [x.^2;x;ones(1,length(x))]';
- Y = y';
- lambda1 = (X'*X)\X'*Y;
- % evaluate the esimated model
- ye1 = X*lambda1;
- hold on;
- plot(x,ye1,'c-o','LineWidth',1.5);
- legend('model truth','observation', 'order-2 poly fitting');
- %% 四階曲線擬合
- X = [x.^4;x.^3;x.^2;x;ones(1,length(x))]';
- Y = y';
- lambda2 = (X'*X)\X'*Y;
- % evaluate the esimated model
- ye2 = X*lambda2;
- hold on;
- plot(x,ye2,'r-o','LineWidth',1.5);
- legend('model truth','observation', 'order-2 poly fitting','order-4 poly fitting');
- %% 八階曲線擬合
- X = [x.^8;x.^7;x.^6;x.^5;x.^4;x.^3;x.^2;x;ones(1,length(x))]';
- Y = y';
- lambda3 = (X'*X)\X'*Y
- % evaluate the esimated model
- ye3 = X*lambda3;
- a=ye3'-y;
- a1=20*log10(a);
- hold on;
- plot(x,ye3,'b-o','LineWidth',1.5);
- xlabel('Fs');
- ylabel('幅頻值');
- legend('model truth','observation', 'order-2 poly fitting','order-4 poly fitting','order-8 poly fitting');
- %擬合的1/sinc曲線與理想曲線的誤差范圍
- figure;
- plot(x,-20*log10(y./abs(a)));
- xlabel('Fs');
- ylabel('1/sinc擬合誤差(dB)');
- title('1/sinc擬合誤差');
- %% 補償后的誤差
- b=ye3'.*sinc(x);
- figure;
- subplot(2,1,1);
- plot(x,sinc(x),x,b);
- xlabel('Fs');
- ylabel('幅頻');
- title('補償后對比');
- subplot(2,1,2);
- plot(x,-20*log10(1./(1-b)));
- xlabel('Fs');
- ylabel('補償后的誤差(dB)');
- title('補償后的誤差');
- %% show future trends
- %X = [x_all;ones(1,length(x_all))]';
- %ye1 = X*lambda1;
- %X = [x_all.^3;x_all.^2;x_all;ones(1,length(x_all))]';
- %ye2 = X*lambda2;
- %X = [x_all.^5;x_all.^4;x_all.^3;x_all.^2;x_all;ones(1,length(x_all))]';
- %ye3 = X*lambda3;
- %figure;
- %plot(x_all,y_truth_all,'g-x',x_all,y_all,'m-x',x_all,ye1,'c-o',x_all,ye2,'r-o',x_all,ye3,'b-o','LineWidth',1.5);
- %legend('model truth','observation', 'order-1 poly fitting','order-3 poly fitting', 'order-5 poly fitting');
- %title('testing');
- …………限于本文篇幅 余下代碼請從51黑下載附件…………
復制代碼
所有資料51hei提供下載:
demo_experiment1.zip
(933 Bytes, 下載次數: 11)
2017-7-2 20:33 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
|