拉格朗日插值法matlab函数

来源:互联网 发布:淘宝商品销量排行 编辑:程序博客网 时间:2024/05/29 18:43
%拉格朗日插值法
n=input('please input the number of nodes n:');
x=zeros(1,n);
y=x;
L=x;
for i=1:n
    disp(['x','(',num2str(i),')='])
    x(i)=input(':');
    disp(['y','(',num2str(i),')='])
    y(i)=input(':');
    
end
X=input('please input X:\n');
for i=1:n
    if X-x(i)==0
        disp('error! you should input another X');
        X=input('please input X:\n');
        
    end
end
    
p=ones(1,n);
q=p;
for j=1:n
    for i=1:n
     p(j)=p(j)*(X-x(i));
    end
    p(j)=p(j)/(X-x(j));
    for i=1:n
        if i==j
            q(j)=q(j);
        else q(j)=q(j)*(x(j)-x(i));
        end
    end
    L(j)=y(j)*p(j)/q(j);
end
Y=sum(L);
disp(['The result is Y=',num2str(Y)])