Matlab 中的多项式回归和绘图
Polynomial regression and plotting in Matlab
给定一组点 x
和一组值 y
,我试图计算最小二乘意义上最适合 P(x) = y
的多项式。该函数应显示 Vandermonde 矩阵,输出多项式 c
应绘制为 p (x) = c0*x^0 + c1*x^1 + c2*x^2 + .. 形式的函数... + cn-1^(n-1).
我想清楚地看到绘制函数的同一个图上的点 (xi,yi)。
这是我到目前为止尝试过的方法:
function c = interpolation(x, y)
n = length(x);
V = ones(n);
for j = n:-1:2
V(:,j-1) = x.*V(:,j);
end
c = V \ y;
disp(V)
for i = 0:n-1
fprintf('c%d= %.3f\n', i, c(i+1));
end
x = linspace(-1,2,-100);
y = polyval(c,x);
x0 = x;
y0 = polyval(c,x0);
plot(x,y,'b-')
hold on;
plot(x0,y0,'ro')
hold off;
您想看一下 polyval
and linspace
if you don't already know it. Also take a look at polyfit
,它会根据给定的度数为您进行插值。这是您更正后的代码:
function [p,V] = interpolation(x0,y0,N)
% format the inputs as columns
x0 = x0(:);
y0 = y0(:);
% Build up the vandermonde matrix
n = numel(x0);
disp('Vandermonde matrix:');
V = fliplr(bsxfun( @power, x0, 0:(n-1) ))
% compute the coefficients of the fitting polynomial
p = V \ y0;
% plot the polynomial using N values
x = linspace( min(x0), max(x0), N );
y = polyval(p,x);
plot(x,y,'b-'); hold on;
plot(x0',y0','ro'); hold off;
end
注意:返回为 p
的多项式系数与您的索引相比是相反的,即它们按降幂排序。
给定一组点 x
和一组值 y
,我试图计算最小二乘意义上最适合 P(x) = y
的多项式。该函数应显示 Vandermonde 矩阵,输出多项式 c
应绘制为 p (x) = c0*x^0 + c1*x^1 + c2*x^2 + .. 形式的函数... + cn-1^(n-1).
我想清楚地看到绘制函数的同一个图上的点 (xi,yi)。
这是我到目前为止尝试过的方法:
function c = interpolation(x, y)
n = length(x);
V = ones(n);
for j = n:-1:2
V(:,j-1) = x.*V(:,j);
end
c = V \ y;
disp(V)
for i = 0:n-1
fprintf('c%d= %.3f\n', i, c(i+1));
end
x = linspace(-1,2,-100);
y = polyval(c,x);
x0 = x;
y0 = polyval(c,x0);
plot(x,y,'b-')
hold on;
plot(x0,y0,'ro')
hold off;
您想看一下 polyval
and linspace
if you don't already know it. Also take a look at polyfit
,它会根据给定的度数为您进行插值。这是您更正后的代码:
function [p,V] = interpolation(x0,y0,N)
% format the inputs as columns
x0 = x0(:);
y0 = y0(:);
% Build up the vandermonde matrix
n = numel(x0);
disp('Vandermonde matrix:');
V = fliplr(bsxfun( @power, x0, 0:(n-1) ))
% compute the coefficients of the fitting polynomial
p = V \ y0;
% plot the polynomial using N values
x = linspace( min(x0), max(x0), N );
y = polyval(p,x);
plot(x,y,'b-'); hold on;
plot(x0',y0','ro'); hold off;
end
注意:返回为 p
的多项式系数与您的索引相比是相反的,即它们按降幂排序。