给定一组点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= %.3fn', 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
和linspace
,你还想看看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
,与索引相比是相反的,即它们按递减幂排序。