写一个matlab实现拉格朗日插值的算法
时间: 2024-05-13 17:16:45 浏览: 83
以下是MATLAB实现拉格朗日插值的代码:
```matlab
function [p] = LagrangeInterpolation(x, y, xi)
% x: interpolation nodes
% y: interpolation values
% xi: evaluation points
% p: interpolated values at xi
n = length(x);
m = length(xi);
% initialize result
p = zeros(m, 1);
% loop over evaluation points
for i = 1:m
% loop over interpolation nodes
for j = 1:n
% calculate Lagrange basis polynomial
L = 1;
for k = 1:n
if k ~= j
L = L .* (xi(i) - x(k)) ./ (x(j) - x(k));
end
end
% add contribution of current node to interpolated value
p(i) = p(i) + y(j) .* L;
end
end
end
```
使用方法示例:
```matlab
% define interpolation nodes and values
x = [0 1 2 3];
y = [1 0 2 1];
% define evaluation points
xi = linspace(0, 3, 101);
% interpolate at evaluation points
p = LagrangeInterpolation(x, y, xi);
% plot original function and interpolated function
plot(x, y, 'o', xi, p, '-')
```
阅读全文