用Matlab实现的拉格朗日插值并用函数plot绘制函数及其插值函数的图形,分别计算[-5,5]中等分点上的值
时间: 2024-03-19 15:44:56 浏览: 135
好的,我可以帮你解决这个问题。
首先,我们需要定义一个函数,用于计算拉格朗日插值:
```matlab
function y = lagrange_interp(x, xdata, ydata)
% x: 插值点
% xdata: 已知数据点的横坐标
% ydata: 已知数据点的纵坐标
n = length(xdata);
L = ones(n, length(x));
for j = 1:n
for k = [1:j-1 j+1:n]
L(j,:) = L(j,:) .* (x - xdata(k)) / (xdata(j) - xdata(k));
end
end
y = 0;
for j = 1:n
y = y + ydata(j) * L(j,:);
end
```
接下来,我们可以定义一个测试函数,例如 $f(x) = \sin(x)$:
```matlab
f = @(x) sin(x);
```
然后,我们可以在 $[-5,5]$ 中等分 $n$ 个点,这里我们取 $n=100$:
```matlab
n = 100;
xdata = linspace(-5, 5, n);
ydata = f(xdata);
```
现在,我们可以用这些点来构建拉格朗日插值,并在 $[-5,5]$ 中等分 $m$ 个点,这里我们取 $m=1000$:
```matlab
m = 1000;
x = linspace(-5, 5, m);
y = lagrange_interp(x, xdata, ydata);
```
最后,我们可以用函数 `plot` 绘制原函数和插值函数的图形:
```matlab
plot(x, f(x), 'b-', x, y, 'r--');
legend('原函数', '插值函数');
```
完整代码如下:
```matlab
function y = lagrange_interp(x, xdata, ydata)
% x: 插值点
% xdata: 已知数据点的横坐标
% ydata: 已知数据点的纵坐标
n = length(xdata);
L = ones(n, length(x));
for j = 1:n
for k = [1:j-1 j+1:n]
L(j,:) = L(j,:) .* (x - xdata(k)) / (xdata(j) - xdata(k));
end
end
y = 0;
for j = 1:n
y = y + ydata(j) * L(j,:);
end
f = @(x) sin(x); % 测试函数
n = 100;
xdata = linspace(-5, 5, n);
ydata = f(xdata);
m = 1000;
x = linspace(-5, 5, m);
y = lagrange_interp(x, xdata, ydata);
plot(x, f(x), 'b-', x, y, 'r--');
legend('原函数', '插值函数');
```
这样,我们就得到了在 $[-5,5]$ 中等分点上的原函数和插值函数的图形,并计算了插值函数在这些点上的值。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)