%
%  Lagrange, 分段线性和三次样条
%
x0 = [0 3 5 7 9 11 12 13 14 15];
y0 = [0 1.2 1.7 2.0 2.1 2.0 1.8 1.2 1.0 1.6];
x = 0:0.1:15;
y1 = lagrange(x0,y0,x); % Lagrange 插值
y2 = interp1(x0,y0,x);  % 分段线性插值
y3 = interp1(x0,y0,x,'spline'); % 三次样条
subplot(2,2,1), plot(x0,y0,'+','linewidth',2), title('散点图','fontsize',14);
subplot(2,2,2), plot(x0,y0,'+',x,y1,'linewidth',2), title('Lagrange','fontsize',14);
subplot(2,2,3), plot(x0,y0,'+',x,y2,'linewidth',2), title('分段线性','fontsize',14);
subplot(2,2,4), plot(x0,y0,'+',x,y3,'linewidth',2), title('三次样条','fontsize',14);


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