I'm trying to construct a polynomial in MATLAB using Newton's Interpolating Divided Difference Formula, and in doing so, generalize it to any size vector x and y. So far i was able to obtain the coefficients for the polynomial, but i'm unsure how to construct the polynomial itself. Here's what i've done so far:
%% Divided Difference Generalization
% Example:
% Construct a Divided Difference Table for x0=2, x1=-1, x2=-6 and
% f(x)=x^2+4x-5
% x | 0th DD | 1'st DD | 2nd DD |
% 2 | 7 | | |
% -1 | -8 | -5 | |
% -6 | 7 | -3 | 1 |
x=[2 -1 -6];
y=[7 -8 7];
size=length(x);
d=zeros(size,size);
xlength=length(x);
DDlim=length(x)-1;
D=zeros(xlength,xlength)
D(:,1)=y;
for i=1:DDlim
for j=1:i
D(i+1,j+1)=(D(i+1,j)-D(i,j))/(x(i+1)-x(i-j+1));
end
end
a=diag(D);
I'm trying to construct a general polynomial from the coefficents i've obtained from a to become: \begin{eqnarray} P_{2}(x) &&=&& 7+5(x-2)+1(x-2)(x+1)\\ &&=&& x^2+4x-5 \end{eqnarray}
And have it work for any number of points.
I'd appreciate any tips or help on to how to construct these polynomials without actually having to hardcode them. Thank you.
Add this additional code and you will be able to achieve what you are hoping to get,hopefully:
expr = poly2sym(a) ;% This create polynomial from the coefficient matrix
fpe = fplot(expr);
title(fpe.DisplayName)
hold on
plot(x,y,'*')