我在MATLAB上为我的作业编写了这个代码,用三对角矩阵进行三次样条插值。我按照算法的所有步骤操作,我真的没有找到我的错误。 它可以用二级函数编写,但是当我放置sin(x)时,结果不是样条曲线而且不知道为什么,因为使用其他函数我没有问题。任何人都可以帮我找到错误吗?感谢
CUBIC SPLINE SCRIPT:
close all
clear all
clf reset
ff = @(x) sin(x);
x = [-2 0 2 4 6 7 8 9 10 11 12];
for i = 1: length(x),
omega(i) = ff(x(i));
end
n = length(x);
h = zeros(n - 1, 1);
for i = 1: n - 1,
h(i) = x(i + 1) - x(i);
end
a = zeros(n, 1);
b = zeros(n, 1);
d = zeros(n, 1);
f = zeros(n, 1);
for j = 2: n - 1,
a(j) = 2*(h(j) + h(j - 1));
b(j) = h(j - 1);
d(j) = h(j);
f(j) = 6 * (omega(j + 1) - omega(j) / h(j)) - (6 * (omega(j) - omega(j - 1)) / h(j - 1));
end
% Starting conditions
a(1) = -2;
f(1) = 0;
a(n) = 4;
f(n) = 0;
% Coefficents
c = tridiag(a, b, d, f);
t = linspace (x(1), x(n), 301);
for k = 1: length(t),
tk = t(k);
y(k) = spline_aux(x, omega, c, tk);
z(k) = ff(tk);
end
plot(t, z, 'b-', 'linewidth', 2)
hold on;
plot(t, y, 'r.', x, omega, 'go')
grid on
TRIADIAGONAL MATRIX:
function [x] = tridiag(a, b, d, f)
n = length(f);
alfa = zeros(n, 1);
beta = zeros(n, 1);
alfa(1) = a(1);
for i = 2: n,
beta(i) = b(i) / alfa(i - 1);
fprintf (' i: %d beta: %12.8f\n', i, beta(i))
alfa(i) = a(i) - (beta(i)*d(i - 1));
fprintf (' i: %d alfa: %12.8f\n', i, alfa(i))
end
y(1) = f(1);
for i = 2: n,
y(i) = f(i) - beta(i)*y(i - 1);
end
x(n) = y(n) / alfa(n);
for i = n - 1: 1,
x(i) = (y(i) - (d(i)*x(i + 1))) / alfa(i);
end
tk点的样条评估:
function [s] = spline_aux(x, w, c, tk)
n = length(x);
h = zeros(n - 1, 1);
for i = 1: n - 1,
h(i) = x(i+1) - x(i);
end
for i = 1: n - 1,
if (x(i) <= tk && tk <= x(i+1))
break
end
end
s1 = c(i)*((x(i+1) - tk)^3)/(6*h(i));
s2 = c(i+1)*((tk - x(i))^3)/(6*h(i));
s3 = (w(i)/h(i) - (c(i)*h(i)/6))*(x(i+1) - tk);
s4 = (w(i+1)/h(i) - (c(i+1)*h(i)/6))*(tk - x(i));
s = s1 + s2 + s3 + s4;
答案 0 :(得分:0)
那是因为您没有正确使用Matlab&#39; for
在函数function [x] = tridiag(a, b, d, f)
最后的for
读取for i = n - 1: 1
但是永远不会执行,你要写道:
for i = n - 1:-1:1
然后工作。您应该注意到它在以前的任何尝试中都有效,而不仅仅是sin(x)