Cubic Spline Code
Cubic Spline Code
b = zeros(n-1,1);
for i = 1:n-1
b(i) = (1/h(i))*(y(i+1)-y(i)) - (1/3*h(i))*(2*c(i)+c(i+1));
end
% Coefficient vector dj:
d = zeros(n-1,1);
for i = 1:n-1
d(i) = (1/(3*h(i))) * (c(i+1)-c(i));
end
% Plotting results:
k = 100;
for i = 1:n-1
f = @(x) y(i) + b(i).*(x-x(i)) + c(i).*(x-x(i)).^2 + d(i).*(xx(i)).^3;
xf = linspace(x(i),x(i+1),k);
plot(xf,f(xf),'b');
plot(xf,f(xf)-sin(2*pi*xf),'-') % Plotting error
end
% Given a value on the x-axis, u, that we wish to know the yvalue of,
% we must first find in which interval u is. We will use
bisection
% search to accomplish this. Interval must be ascending or
descending.
jl = 1;
ju = n;
while (ju - jl > 1)
jm = ceil((jl + ju)/2);
if (u < x(jm))
ju = jm;
else
jl = jm;
end
end
end