这里有没有人能帮我解决以下问题?下面的代码计算适合给定数据集的最佳多项式,即指定次数的多项式。
不幸的是,无论数据集是什么,通常是6度或更高,MATLAB得到的是一个完全错误的拟合。通常,拟合曲线完全远离数据,以一种指数方式向下看。(参见示例: degree = 8)。
x=[1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5] % experimental x-values
y=[4.3 6.2 10.1 13.5 19.8 22.6 24.7 29.2] % experimental y-values
degree=8; % specify the degree
A = zeros(length(x),degree);
for exponent=0:degree;
for data=1:length(x);
A(data,exponent+1)=x(data).^exponent; % create matrix A
end;
end;
a=inv((transpose(A)*A))*transpose(A)*y'; % a are the coëfficients of the polynom
a=flipud(a);
fitpolynoom=polyval(a,x);
error=sum((y-fitpolynoom).^2); % calculates the fit-error using the least-squares method
fitpolynoom=polyval(a,x);
figure;
plot(x,y,'black*',x,fitpolynoom,'g-');
error % displays the value of the fit-error in the Matlab command window提前谢谢。

发布于 2014-12-16 23:21:58
首先,注意:对于Matlab中的最小二乘拟合多项式,可以使用现有的polyfit函数。此外(这可能取决于你的应用),你可能不应该拟合$8$次多项式,特别是当你有$8$数据点的时候。在这个答案中,我假设你有很好的理由将多项式拟合到你的数据中(例如,只是为了自学目的)。
这个问题是一个由矩阵求逆引起的数值问题。对于求解$Ax=b$类型的方程,其中$A$是一个方阵,实际上不建议对$A$求逆(请参见Blogpost 'Don't invert that matrix' by John D. Cook)。在最小二乘情况下,不是开始{方程}a= (A^\mathrm{T} A)^{-1} A^\mathrm{T} y^\mathrm{T} \end{方程},而是用其他方法求解\begin{方程} (A^\mathrm{T} A)a = A^\mathrm{T} y^\mathrm{T} \end{方程}。在你的MATLAB代码中,你可以替换
a=inv((transpose(A)*A))*transpose(A)*y';通过
a = (transpose(A) * A) \ (transpose(A) * y');通过对您的代码进行此修改,我通过数据点获得了一个合适的结果。
https://stackoverflow.com/questions/27508361
复制相似问题