polyfit和polyval函数

时间:2019-05-09 15:27:15

标签: matlab curve-fitting

你好,我的问题是关于P3(x)的曲线拉伸,我使用polyfit和polyval函数编写代码,但我需要不使用这些函数来编写代码。

这是我编写的代码

n=input('Enter a value: ');
if(n<3)
    fprintf('Enter a different value larger than 3')
end 
if(n>=3)
x = 1:n; 
y = -0.3*x + 2*randn(1,n); 
[p,S] = polyfit(x,y,3);
[y_fit,delta] = polyval(p,x,S);
plot(x,y,'bo')
hold on
plot(x,y_fit,'r-')
title('Linear-Fit Output')
legend('Data','Linear Fit')
end

这是我编写的能正常工作的代码,但我想不用使用polfite和polyval函数来编写它

1 个答案:

答案 0 :(得分:3)

不使用符号

y = a0*x^0 + a1*x^1 + a2*x^2 + a3*x^3
For n data point --> y = X*a 

其中

X = [x1^0 , a1*x1^1, a2*x1^2 , a3*x1^3; x2^0 , a1*x2^1, a2*x2^2 , a3*x2^3;...;xn^0 , a1*xn^1 , a2*xn^2 , a3*xn^3 ]

a = [a0, a1, a2, a3]; y = [y1, y2, ..., yn] a的计算如下

y = X*a ---> a = X\y

代码如下

n is given 
x = 1:n; 
y = -0.3*x + 2*randn(1,n);
x0 = ones(n, 1);
x1 = x';
x2 = (x.^2)';
x3 = (x.^3)';
X = [x0 x1 x2 x3];
a = X\(y');
f =@(t)a(1) + a(2).*t + a(3).*(t.^2)+ a(4).*(t.^3);

使用最小二乘法查找最佳拟合三次多项式

n=input('Enter a value: ');
if(n<3)
    fprintf('Enter a different value larger than 3')
else
    x = 1:n; 
    y = -0.3*x + 2*randn(1,n);
    % Cubic regression

    syms a0 a1 a2 a3

    yq = a0 + a1.*x + a2.*(x.^2) + a3.*(x.^3) ;
    rq = yq - y;
    f = sum(rq.^2);
    fa0 = diff(f,a0);
    fa1 = diff(f,a1);
    fa2 = diff(f,a2);
    fa3 = diff(f,a3);
    sol = solve(fa0 == 0, fa1 == 0, fa2 == 0, a0, a1, a2, a3);
    a0 = sol.a0;
    a1 = sol.a1;
    a2 = sol.a2;
    a3 = sol.a3;

    % Cubic Regression  Curve Function

    f =@(t)a0 + a1.*t + a2.*(t.^2)+ a3.*(t.^3);

    % Plot Data and Cubic Regression Curve
    h = figure(1);
    % Data
    plot3 = scatter(x, y, 100, '+', 'MarkerEdgeColor', 'red', 'linewidth', 5);
    hold on
    % cubic Regression Curve
    xx = linspace(0,n,100);
    plot4 = plot(xx, f(xx), 'linewidth', 5);
    [~,b] = legend([plot3 plot4],{'Real Data','Cubic Regression'}, 'FontSize',30);
    set(findobj(b,'-property','MarkerSize'),'MarkerSize',30);

    xlabel('x-axis','color', 'k', 'fontSize', 25)
    ylabel('y-axis', 'color','k', 'fontSize', 25)
    hYLabel = get(gca,'YLabel');
    set(hYLabel,'rotation',0,'VerticalAlignment','middle',  'HorizontalAlignment','right')
    grid on
    grid minor
    set(gca,'FontSize',20)
    set(get(h,'CurrentAxes'),'GridAlpha',0.8,'MinorGridAlpha',0.5);
    xticks(x);
    title('Cubic Regression', 'color', 'r');
    whitebg('w');
end

n = 5

enter image description here

n = 20