找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 3438|回復(fù): 0
收起左側(cè)

matlab中實現(xiàn)最小二乘擬合函數(shù)曲線

[復(fù)制鏈接]
ID:216631 發(fā)表于 2017-7-2 20:34 | 顯示全部樓層 |閱讀模式
通過矩陣計算的方式實現(xiàn)用最小二乘法擬合高次函數(shù)曲線

matlab源程序如下:
  1. clc;
  2. clear;
  3. close all;
  4. %% 取樣并代入曲線

  5. x_all = 0:0.01:1.81;
  6. [y_truth_all,y_all]=unknown_model1(x_all);

  7. N = length(x_all);

  8. %用前半段取樣點訓練并顯示理想值
  9. x = x_all(1:N/2);
  10. y = y_all(1:N/2);
  11. y_truth = y_truth_all(1:N/2);

  12. plot(x,y_truth,'g-x','LineWidth',1.5);
  13. hold on;
  14. plot(x,y,'m-x','LineWidth',1.5);
  15. legend('model truth','observation');
  16. title('training');

  17. %% 二階曲線擬合
  18. X = [x.^2;x;ones(1,length(x))]';
  19. Y = y';
  20. lambda1 = (X'*X)\X'*Y;
  21. % evaluate the esimated model
  22. ye1 = X*lambda1;
  23. hold on;
  24. plot(x,ye1,'c-o','LineWidth',1.5);
  25. legend('model truth','observation', 'order-2 poly fitting');
  26. %% 四階曲線擬合
  27. X = [x.^4;x.^3;x.^2;x;ones(1,length(x))]';
  28. Y = y';
  29. lambda2 = (X'*X)\X'*Y;
  30. % evaluate the esimated model
  31. ye2 = X*lambda2;
  32. hold on;
  33. plot(x,ye2,'r-o','LineWidth',1.5);
  34. legend('model truth','observation', 'order-2 poly fitting','order-4 poly fitting');

  35. %% 八階曲線擬合
  36. X = [x.^8;x.^7;x.^6;x.^5;x.^4;x.^3;x.^2;x;ones(1,length(x))]';
  37. Y = y';
  38. lambda3 = (X'*X)\X'*Y
  39. % evaluate the esimated model
  40. ye3 = X*lambda3;
  41. a=ye3'-y;
  42. a1=20*log10(a);
  43. hold on;
  44. plot(x,ye3,'b-o','LineWidth',1.5);
  45. xlabel('Fs');
  46. ylabel('幅頻值');
  47. legend('model truth','observation', 'order-2 poly fitting','order-4 poly fitting','order-8 poly fitting');
  48. %擬合的1/sinc曲線與理想曲線的誤差范圍
  49. figure;
  50. plot(x,-20*log10(y./abs(a)));
  51. xlabel('Fs');
  52. ylabel('1/sinc擬合誤差(dB)');
  53. title('1/sinc擬合誤差');
  54. %% 補償后的誤差
  55. b=ye3'.*sinc(x);
  56. figure;
  57. subplot(2,1,1);
  58. plot(x,sinc(x),x,b);
  59. xlabel('Fs');
  60. ylabel('幅頻');
  61. title('補償后對比');
  62. subplot(2,1,2);
  63. plot(x,-20*log10(1./(1-b)));
  64. xlabel('Fs');
  65. ylabel('補償后的誤差(dB)');
  66. title('補償后的誤差');
  67. %% show future trends

  68. %X = [x_all;ones(1,length(x_all))]';
  69. %ye1 = X*lambda1;
  70. %X = [x_all.^3;x_all.^2;x_all;ones(1,length(x_all))]';
  71. %ye2 = X*lambda2;
  72. %X = [x_all.^5;x_all.^4;x_all.^3;x_all.^2;x_all;ones(1,length(x_all))]';
  73. %ye3 = X*lambda3;
  74. %figure;
  75. %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);
  76. %legend('model truth','observation', 'order-1 poly fitting','order-3 poly fitting', 'order-5 poly fitting');
  77. %title('testing');
  78. …………限于本文篇幅 余下代碼請從51黑下載附件…………
復(fù)制代碼

所有資料51hei提供下載:
demo_experiment1.zip (933 Bytes, 下載次數(shù): 11)


回復(fù)

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機教程網(wǎng)

快速回復(fù) 返回頂部 返回列表