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)
0 个评论
回答(1 个)
Sambit Supriya Dash
2021-9-25
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Special Values 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!