# To reduce the number of lines

3 views (last 30 days)
SREERAJ WARRIER on 25 Sep 2021
This is a code for interpolation. I would like to minimize the code lines by using summation and product. Can anyone help me?
%% Interpolation
clear all
x = [-2 -1 1 3];
y = [-1 3 -1 19];
syms t;
syms l1 l2 l3 l4;
l1 = ((t-x(2))*(t-x(3))*(t-x(4)))/((x(1)-x(2))*(x(1)-x(3))*(x(1)-x(4)));
l2 = ((t-x(3))*(t-x(4))*(t-x(1)))/((x(2)-x(3))*(x(2)-x(4))*(x(2)-x(1)));
l3 = ((t-x(4))*(t-x(1))*(t-x(2)))/((x(3)-x(4))*(x(3)-x(1))*(x(3)-x(2)));
l4 = ((t-x(1))*(t-x(2))*(t-x(3)))/((x(4)-x(1))*(x(4)-x(2))*(x(4)-x(3)));
PnX = y(1)*l1 + y(2)*l2 + y(3)*l3 + y(4)*l4
Px = simplify(PnX)
figure; fplot(Px)

Sambit Supriya Dash on 25 Sep 2021
x = [-2 -1 1 3];
y = [-1 3 -1 19];
syms t;
for i = 1:length(x)
Num = prod(t-x([1:(i-1) (i+1):end]));
Den = prod(x(i)-x([1:(i-1) (i+1):end]));
l{i} = Num/Den;
end
for j = 1:length(y)
p(j) = y(j)*l{i};
end
PnX = sum(p);
Px = simplify(PnX)
figure; fplot(Px)
##### 2 CommentsShowHide 1 older comment
Sambit Supriya Dash on 25 Sep 2021
l is same for both the cases I guess.