Vectorisation of a Lagrange polynomial

I am trying to vectorise this function of a lagrange polynomial without a for loop. The for loop code gives the right answer but my vectorised code does not. Any help would be appreciated.
function f is the lagrange polynomial to be approximated and x is a set of sample points (10 points).
Vectorised code
function dfdx = diff1(f, x)
b = length(x);
dfdx = nan(size(f));
%initial value
dfdx(1) = ...
%vectorisation to get 2 -> b-1 have formula
j = 2:1:b-1;
dfdx(j) = f(j-1).*(x(j)+x(j+1))/((x(j-1)+x(j)).*(x(j-1)+x(j+1)))...
+f(j).*(2.*x(j)+x(j-1)-x(j+1))/((x(j-1)-x(j-1)).*(x(j)+x(j+1)))...
+f(j+1).*((x(j)+x(j-1))/((x(j+1)+x(j)).*(x(j)-x(j+1))));
%end value
dfdx(b) = ...
end
For loop code code
function dfdx = diff1(f, x)
b = length(x);
dfdx = nan(size(f));
%initial value
dfdx(1) = ...
%vectorisation to get 2 -> b-1 have formula
for j = 2:b-1
dfdx(j) = f(j-1).*(x(j)+x(j+1))/((x(j-1)+x(j)).*(x(j-1)+x(j+1)))...
+f(j).*(2.*x(j)+x(j-1)-x(j+1))/((x(j-1)-x(j-1)).*(x(j)+x(j+1)))...
+f(j+1).*((x(j)+x(j-1))/((x(j+1)+x(j)).*(x(j)-x(j+1))));
end
%end value
dfdx(b) = ...
end
Calling code
x = ...
f = 1 + x + x.^2;
dfdx = diff1(f,x);
absError = abs((1 + 2*x - diff1(f, x)))

Réponses (1)

Alan Stevens
Alan Stevens le 1 Oct 2020
In your expression
dfdx(j) = f(j-1).*(x(j)+x(j+1))./((x(j-1)+x(j)).*(x(j-1)+x(j+1)))...
+f(j).*(2.*x(j)+x(j-1)-x(j+1))./((x(j-1)-x(j-1)).*(x(j)+x(j+1)))...
+f(j+1).*((x(j)+x(j-1))./((x(j+1)+x(j)).*(x(j)-x(j+1))));
You need ./ as well as .*

Catégories

En savoir plus sur Polynomials dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by