I use convolution and for loops (too much for loops) for calculating the interpolation using
Lagrange's method , here’s the main code :
function[p] = lagrange_interpolation(X,Y)
L = zeros(n);
p = zeros(1,n);
% computing L matrice, so that each row i holds the polynom L_i
% Now we compute li(x) for i=0....n ,and we build the polynomial
for k=1:n
multiplier = 1;
outputConv = ones(1,1);
for index = 1:n
if(index ~= k && X(index) ~= X(k))
outputConv = conv(outputConv,[1,-X(index)]);
multiplier = multiplier * ((X(k) - X(index))^-1);
end
end
polynimialSize = length(outputConv);
for index = 1:polynimialSize
L(k,n - index + 1) = outputConv(polynimialSize - index + 1);
end
L(k,:) = multiplier .* L(k,:);
end
% continues
end
Those are too much for loops for computing the l_i(x) (this is done before the last calculation of P_n(x) = Sigma of y_i * l_i(x)) .
Any suggestions into making it more matlab formal ?
Thanks
Yeah, several suggestions (implemented in version 1 below):
ifloop can be combined withforabove it (just makeindexskipkvia something likejr(jr~=j)below);polynomialSizeis always equallength(outputConv)which is always equaln(because you havendatapoints,(n-1)thpolynomial withncoefficients), so the lastforloop and next line can be also replaced with simpleL(k,:) = multiplier * outputConv;So I replicated the example on http://en.wikipedia.org/wiki/Lagrange_polynomial (and adopted their
j-mnotation, but for mejgoes1:nandmis1:nandm~=j), hence my initialization looks likethen v 1.0 looks like
which can be further simplified if you realize that numerator of l_j(x) is just a polynomial with specific roots – for that there is a nice command in matlab –
poly. Similarly the denominator is just that polyn evaluated at X(j) – for that there ispolyval. Hence, v 1.9:Why version 1.9 and not 2.0? well, there is probably a way to get rid of this last for loop, and write it all in 1 line, but I can’t think of it right now – it’s a todo for v 2.0 🙂
And, for dessert, if you want to get the same picture as wikipedia:
produces
enjoy and feel free to reuse/improve