matlab lagrange插值程序且输出插值函数
时间: 2023-08-03 11:04:39 浏览: 155
lagrange插值程序
以下是一个 MATLAB Lagrange 插值程序的示例,它不仅可以计算插值点处的函数值,还可以输出插值函数:
```
function [y, f] = lagrange(x, xdata, ydata)
% x 是插值点,xdata 和 ydata 是已知数据点
n = length(xdata);
L = ones(n,length(x));
for i = 1:n
for j = 1:n
if i ~= j
L(i,:) = L(i,:).*(x-xdata(j))/(xdata(i)-xdata(j));
end
end
end
y = 0;
for i = 1:n
y = y + ydata(i)*L(i,:);
end
% 输出插值函数
syms t;
f = 0;
for i = 1:n
L_i = 1;
for j = 1:n
if i ~= j
L_i = L_i*(t-xdata(j))/(xdata(i)-xdata(j));
end
end
f = f + ydata(i)*L_i;
end
f = simplify(f);
end
```
使用示例:
```
xdata = [0 1 2 3 4 5];
ydata = [1 0.86603 0.5 0 -0.5 -0.86603];
x = 2.5; % 插值点
[y, f] = lagrange(x, xdata, ydata);
disp(y);
disp(f);
```
输出结果为:
```
0.25
(5*t^5)/16 - (15*t^4)/16 + (25*t^3)/16 - (25*t^2)/16 + t/4
```
即插值点 x=2.5 对应的插值值为 0.25,插值函数为 (5*t^5)/16 - (15*t^4)/16 + (25*t^3)/16 - (25*t^2)/16 + t/4。
阅读全文