使用for循环进行多项式的曲线拟合,直到度i?

时间:2019-12-03 00:48:38

标签: matlab matlab-figure curve-fitting

我有这个硬编码版本,可以将数据拟合为线性,二次和三次多项式的曲线:

对于某些数据x和函数y

M=[x.^0 x.^1];
L=[x.^0 x.^1 x.^2];

linear = (M'*M)\(M'*y);
plot(x, linear(1)+linear(2)*x, ';linear;r');

deg2 = (L'*L)\(L'*y);
plot(x, deg2(1)+deg2(2)*x+deg2(3)*(x.*x), ';quadratic plot;b');

我想知道如何将其转换为for循环以绘制n次多项式的曲线?我卡住的部分是绘图部分,如何将系数的增加转化为for循环?

我有什么:

for i = 1:5 % say we're trying to plot curves up to degree 5 polynomials...
    curr=x.^(0:i);
    degI = (curr'*curr)\(curr'*y);
    plot(x, ???)  % what goes in here<-
end

2 个答案:

答案 0 :(得分:0)

如果只是绘图,则可以使用polyval函数通过提供系数向量来评估所需等级的多项式

% For example, some random coefficients for a 5th order polynomial
% degI = (curr'*curr)\(curr'*y)  % Your case 
degi = [3.2755 0.8131 0.5950 2.4918 4.7987 1.5464]; % for 5th order polynomial

x = linspace(-2, 2, 10000);

hold on
% Using polyval to loop over the grade of the polynomials
for i = 1:length(degI)
    plot(x, polyval(degI(1:i), x))
end

在一个图中给出所有多项式

enter image description here

答案 1 :(得分:0)

我相信这应该可以准确回答您的问题。您只需要注意矩阵维度。

for i = 1:5
    curr=x.^(0:i);
    degI = (curr'*curr)\(curr'*y);
    plot(x, x.^(0:i)*degI)
end