y=[110.49 73.72 23.39 17.11 20.31 29.37 74.74 117.02 298.04 348.13 294.75 253.78 250.48 239.48 236.52 245.04 286.74 304.78 288.76 247.11 216.73 185.78 171.19 171.73 164.05];
x=[0:1:24];
scatter(x,y,'r','filled');
xlabel 'x轴'
ylabel 'y轴'
title '多项式最小二乘法拟合'
hold on;
n=10;
a=get_a(x,y,n);
y_pred=compute_y_pred(a,x);
plot(x,y_pred,'b');
ye=y-y_pred; % 计算误差
ye2s=sum(ye.^2); % 误差的平方和
fprintf('误差的平方和=%d',ye2s);
function [a]=get_a(x,y,n)
%计算多项式系数矩阵
%n为拟合的阶数
[~,col]=size(x);
m=col-1;
[A,B]=generate_A_B(m,n,x,y);
a=inv(A)*B';
function [A,B]=generate_A_B(m,n,x,y)
%生成A,B矩阵
A=zeros(n+1);
for j=1:n+1
for i =1:n+1
for k=1:m+1
A(j,i)=A(j,i)+x(k)^(j+i-2);
end
end
end;
B=zeros(1,n+1);
for j=1:n+1
for i =1:m+1
B(j)=B(j)+y(i)*x(i)^(j-1);
end
end
function [ y_pred ] = compute_y_pred( a,x )
%计算多项式拟合的值
[row,~]=size(a);
y_pred=0;
for i=1:row
y_pred=y_pred+a(i)*x.^(i-1);
%y_pred=a(1)+a(2)*x+a(3)*x.^2+a(4)*x.^3+a(5)*x.^4+a(6)*x.^5;
end
多项式最小二乘法拟合曲线【matlab】
最新推荐文章于 2024-07-24 22:33:54 发布