用matlab写一个三次样条插值
时间: 2023-11-04 10:06:03 浏览: 88
以下是一个简单的三次样条插值的Matlab代码:
```matlab
% 三次样条插值
% 输入:x、y为数据点横纵坐标,xx为插值点横坐标
% 输出:yy为插值点纵坐标
function yy = cubicSpline(x, y, xx)
n = length(x);
% 计算h和b
h = zeros(n-1, 1);
b = zeros(n-1, 1);
for i = 1:n-1
h(i) = x(i+1) - x(i);
b(i) = (y(i+1) - y(i)) / h(i);
end
% 计算矩阵A和向量r
A = zeros(n);
r = zeros(n, 1);
A(1, 1) = 1;
A(n, n) = 1;
for i = 2:n-1
A(i, i-1) = h(i-1);
A(i, i) = 2*(h(i-1) + h(i));
A(i, i+1) = h(i);
r(i) = 6*(b(i) - b(i-1));
end
% 解方程
M = A \ r;
% 计算各段的系数
a = y;
b = b - h .* (2*M(1:n-1) + M(2:n)) / 6;
c = M / 2;
d = (M(2:n) - M(1:n-1)) ./ (6*h);
% 插值
yy = zeros(size(xx));
for i = 1:length(xx)
% 找到插值点所在的段
j = find(x <= xx(i), 1, 'last');
if j == n
j = n - 1;
end
% 计算插值点的函数值
t = xx(i) - x(j);
yy(i) = a(j) + b(j)*t + c(j)*t^2 + d(j)*t^3;
end
end
```
使用方法:
```matlab
% 定义数据点
x = [0, 1, 2, 3, 4];
y = [1, 2.5, 3, 2, 1];
% 定义插值点
xx = linspace(0, 4, 101);
% 进行插值
yy = cubicSpline(x, y, xx);
% 绘图
plot(x, y, 'o', xx, yy);
```
阅读全文