Reputation: 843
I've made a code to calculate the result of divided differences method and lagrange method by interpolating points. I would also like to build a polynomial using symbolic variables but how can I accomplish this?
function dividedDifferences(X,Y,x)
ddMatrix = X'
ddMatrix(:,2) = Y'
for j=3:length(Y)+3
for i=1:length(Y)+2-j
ddMatrix(i,j) = (ddMatrix(i,j-1)-ddMatrix(i+1,j-1))/(ddMatrix(i,1)-ddMatrix(i+j-2,1))
end
end
disp(ddMatrix)
Px = 0
for j=2:length(Y)+1
prd = 1
for i=1:j-2
prd = prd * (x - ddMatrix(i,1))
end
Px = Px + ddMatrix(1,j)*prd
end
disp(Px)
endfunction
function lagrange(X,Y,x)
for i=1:length(Y)
l(i)=1
for j=1:length(Y)
if i~=j
l(i) = l(i)*(x-X(j))/(X(i)-X(j))
end
end
end
disp(l')
L=0
for i=1:length(Y)
L = L+Y(i)*l(i)
end
disp(L)
endfunction
//example instance
X = [0 1 5 8]
Y = [0 1 8 16.4]
x = 7
dividedDifferences(X,Y,x)
lagrange(X,Y,x)
Upvotes: 3
Views: 746
Reputation:
To create a symbolic polynomial, initialize a symbolic variable with x = poly(0,"x")
where x is the name of the variable to use in the polynomial. Then proceed to compute with it exactly as you did in the function lagrange
. I essentially copied your function to symboliclagrange
below, cutting out the numerical parameter and intermediate display:
function symboliclagrange(X,Y)
x = poly(0,"x")
for i=1:length(Y)
l(i)=1
for j=1:length(Y)
if i~=j
l(i) = l(i)*(x-X(j))/(X(i)-X(j))
end
end
end
L=0
for i=1:length(Y)
L = L+Y(i)*l(i)
end
disp(L)
endfunction
With your input X = [0 1 5 8]
, Y = [0 1 8 16.4]
the output is 0.85x+0.15x2, which is the correct interpolating polynomial.
Upvotes: 1