Lagrange Interpolation for 4th order

function ya = Lagrange(x,y,a)
n_x = length(x);
n_y = length(y);
if n_x ~= n_y
error('The size of the x and y vectors are not compatible')
end
y1_num = (y(1,1) .* (a-x(2,1)).*(a-x(3,1)).*(a-x(4,1)).*(a-x(5,1)));
y2_num = (y(2,1) .* (a-x(1,1)).*(a-x(3,1)).*(a-x(4,1)).*(a-x(5,1)));
y3_num = (y(3,1) .* (a-x(1,1)).*(a-x(2,1)).*(a-x(4,1)).*(a-x(5,1)));
y4_num = (y(4,1) .* (a-x(1,1)).*(a-x(2,1)).*(a-x(3,1)).*(a-x(5,1)));
y5_num = (y(5,1) .* (a-x(1,1)).*(a-x(2,1)).*(a-x(3,1)).*(a-x(4,1)));
y1_denom =((x(1,1)- x(2,1)).*(x(1,1)-x(3,1)).*(x(1,1)-x(4,1)).*(x(1,1)-x(5,1)));
y2_denom =((x(2,1)- x(1,1)).*(x(2,1)-x(3,1)).*(x(2,1)-x(4,1)).*(x(2,1)-x(5,1)));
y3_denom =((x(3,1)- x(1,1)).*(x(3,1)-x(2,1)).*(x(3,1)-x(4,1)).*(x(3,1)-x(5,1)));
y4_denom =((x(4,1)- x(1,1)).*(x(4,1)-x(2,1)).*(x(4,1)-x(3,1)).*(x(4,1)-x(5,1)));
y5_denom =((x(5,1)- x(1,1)).*(x(5,1)-x(2,1)).*(x(5,1)-x(3,1)).*(x(5,1)-x(4,1)));
y1 = y1_num./y1_denom;
y2 = y2_num./y2_denom;
y3 = y3_num./y3_denom;
y4 = y4_num./y4_denom;
y5 = y5_num./y5_denom;
ya = y1 + y2 + y3 + y4 + y5;
end
I am trying to run a code for 5 data points and evaluate the given equation at a specific value. I can not figure out how to input the value of "a" from the command window where I am also inputting the arrays (which are both 5X1). And when I do assign a value for a and check the answer with a lagrange calculator online, the y value is wrong. Any help would be appreciated.

Answers (0)

Categories

Find more on App Building in Help Center and File Exchange

Asked:

on 8 Apr 2019

Edited:

on 8 Apr 2019

Community Treasure Hunt

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

Start Hunting!