This is my MATLAB code for divided differences and Hermite interpolation, but it doesn't work properly. Could you take a look at it? Thank you.
I'm sorry for the layout, but it's the best I could do.
function [F,X] = diffdivher(x,fx,df)
X=[];
for i=1:length(x)
X=[X,x(i),x(i)];
end
for i=1:length(f);
F=[F,f(i),f(i)];
end
n=length(x)-1;
N=2*n+1;
for i=N:-2:3
F(i)=(F(i)-F(i-1))/(X(i)-X(i-1));
end
for k=2:N
for i=N+1:-2:k+1
F(i)=(F(i)-F(i-1))/(X(i)-X(i-k));
end
end
end
function [Pval] = herhor(x,f,df,xval)
X=[];
for i=1:length(x)
X=[X,x(i),x(i)];
end
dd=diffdivher(x,f,df);
for i=1:length(xval)
Pval(i)=dd(end);
for j=length(dd)-1:-1:1
Pval(i)=dd(j)+(xval(i)-X(j))*(Pval(i));
end
end
end
Best Answer
I'll assume your formulae are correct, and just give some MATLAB observations. For your
diffdivher
function:F=[];
before usingF
in your second for-loop.length(f)
really shouldn't be there.diffdivher
function receives afx
and adf
, but in your second for-loop you are using af
that came right of nowhere.x
andf
, then it is easier to just assumex
andf
are row vectors, then access each entry asfor y=x
,for z=f
. Also, not the most practical way of sortedly duplicating the entries of a vector; simply doX=[x;x](:)';
.u=N:-2:3;
, thenF(u)=(F(u)-F(u-1))./(X(u)-X(u-1));
. Notice the dot before the slash. Similarly for the inner loop of your fourth for-loop.Observations for your
herhor
function:Pval
before accessingdd(end)
to each entry.