To reduce the number of lines

3 views (last 30 days)
SREERAJ WARRIER
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)

Answers (1)

Sambit Supriya Dash
Sambit Supriya Dash on 25 Sep 2021
This may help you, in terms of looping, addition and substraction,
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 Comments
SREERAJ WARRIER
SREERAJ WARRIER on 25 Sep 2021
The figures are different for both code. The y-limit is different
Sambit Supriya Dash
Sambit Supriya Dash on 25 Sep 2021
l is same for both the cases I guess.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!