首页 > 其他 > 详细

【matlab】 拉格朗日插值

时间:2018-05-05 20:34:43      阅读:239      评论:0      收藏:0      [点我收藏+]

第一个函数  "lagrange1.m"

输入:X Y 与点x0

输出:插值函数对应函数值 y0

function y = lagrange1(X,Y,x0)
n = length(X);
m = length(x0);
for i = 1:m
    z = x0(i);
    s = 0.0;
    for k = 1:n;
        p = 1.0;
        for j = 1:n
            if j~=k
                p = p*(z - X(j))/(X(k)-X(j));
            end
        end
        s = p * Y(k) + s;
    end
    y(i) = s;
end

第二个函数  "lagrange2.m"

输入:X Y 

输出:插值函数

function L = lagrange2(x,y)
m = length(x);
for k = 1:m;
    V = 1;
    for i = 1:m;
        if k~=i
            V = conv(V,poly(x(i)))/(x(k)-x(i));
        end
    end
    l(k,:) = poly2sym(V);
end
L = y * l;

 

"main.m"

一个简单的测试:

x = [1,1.2,1.8,2.5,4];
y =[0.8415,0.9320,0.9738,0.5985,-0.7568];
x0 = [1.6,3];
y0 = lagrange1(x,y,x0)

xx = 0:0.1:5;
yy1 = sin(xx);
yy2 = lagrange1(x,y,xx);
plot(xx,yy1,-r,xx,yy2,-b);
grid
L = lagrange2(x,y);
vpa(L,5)

xx0 = 1:5;
yy0 = lagrange1(x,y,xx0);
yy1 = sin(xx0);
ep = yy1 - yy0

技术分享图片

【matlab】 拉格朗日插值

原文:https://www.cnblogs.com/tao-zhu-forever/p/8995742.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!