% function v=piecelin(x,y,u)
%PIECELIN Piecewise linear interpolation
% v=piecelin(x,y,u) finds the piecewise linear L(x)
% with L(x(j))=y(j) and returns v(k)=L(u(k))
% First divided difference
clear
clc
x=1:6;
y=[16 18 21 17 15 12];
u=[2.5 2 4.5 3.7 5 5.8];
delta=diff(y)./diff(x);
n=length(x);
k=ones(size(u));
for j=2:n-1
k(x(j)<=u)=j
end
s=u-x(k);
v=y(k)+s.*delta(k);
figure
plot(x,y,'*-')
hold on
plot(u,v,'o')
评论19