Created
October 8, 2015 16:35
-
-
Save normalhuman/2a4626a5d34ca84a85e1 to your computer and use it in GitHub Desktop.
Comparison of natural cubic spline and not-a-knot cubic spline for the same data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cubic | |
a = 1992; | |
b = 2000; | |
y = [26 25 20 23 28 21 15 20 18]; | |
n = length(y); | |
h = (b-a)/(n-1); | |
rhs = (-6/h^2)*[0; diff(y',2); 0]; | |
A = diag(4*ones(1,n))+diag(ones(1,n-1),1)+diag(ones(1,n-1),-1); | |
A(1, 1:2) = [1 0]; | |
A(n, n-1:n) = [1 0]; | |
plotspline(a, b, y, A\rhs, 'b'); | |
hold on | |
A(1, 1:3) = [1 -2 1]; | |
A(n, n-2:n) = [1 -2 1]; | |
plotspline(a, b, y, A\rhs, 'r'); | |
legend('natural', 'not-a-knot') | |
plot(a:h:b, y, 'm*'); | |
end | |
function plotspline(a,b,y,z,color) | |
h = (b-a)/(length(y)-1); | |
allx = []; | |
spline = []; | |
for i = 1:length(y)-1 | |
xL = a+h*(i-1); | |
xR = a+h*i; | |
x = linspace(xL, xR); | |
linear = y(i)*(xR-x)/h + y(i+1)*(x-xL)/h; | |
correction = ((z(i+1)+2*z(i))*(xR-x)+(2*z(i+1)+z(i))*(x-xL)).*(xR-x).*(x-xL)/(6*h); | |
allx = [allx, x]; | |
spline = [spline, linear+correction]; | |
end | |
plot(allx, spline, color); | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment