To reduce the number of lines

4 次查看(过去 30 天)
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)

回答(1 个)

Sambit Supriya Dash
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 个评论
SREERAJ WARRIER
SREERAJ WARRIER 2021-9-25
The figures are different for both code. The y-limit is different
Sambit Supriya Dash
l is same for both the cases I guess.

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by