Skip to content

Instantly share code, notes, and snippets.

View normalhuman's full-sized avatar

Normal Human normalhuman

View GitHub Profile
@normalhuman
normalhuman / twocubicsplines.m
Created October 8, 2015 16:35
Comparison of natural cubic spline and not-a-knot cubic spline for the same data
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];
@normalhuman
normalhuman / naturalcubic.m
Last active October 8, 2015 16:29
Natural cubic spline as piecewise linear + correction term
function naturalcubic
a = 1995;
b = 2000;
y = [30 25 20 28 15 31];
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) = [0 1];
function adaptivePL
t = linspace(0, 7, 1000); % the default number of points, 100, may be not enough here
points = refine(t(1), t(end)); % determine the nodes of interpolation
plot(points, f(points), 'r-*') % piecewise linear plot with asterisks for data points
hold on
plot(t, f(t)) % the original function for comparison
end
function points = refine(x1,x2)
xm = (x1+x2)/2;
@normalhuman
normalhuman / chebyshev_interpolation.m
Created September 25, 2015 01:57
Polynomial interpolation using Chebyshev nodes
function chebyshev_interpolation
a = -5;
b = 5;
t = linspace(a,b);
plot(t, [chebyshev(a,b,5,t); chebyshev(a,b,10,t); chebyshev(a,b,15,t); chebyshev(a,b,30,t)]);
hold on
plot(t, f(t), 'k--'); % original function in dashed black curve
legend('degree 5', 'degree 10', 'degree 15', 'degree 30', 'function') % describe the curves
end
@normalhuman
normalhuman / plot_newton.m
Created September 19, 2015 23:26
Plots the Newton polynomial interpolating a given function (and shows the Runge phenomenon)
function plot_newton
f = @(x) 1./(1+x.^2); % function to interpolate
x = -5:5; % nodes of interpolation
y = f(x);
c = coeff(x,y); % calculate Newton polynomial coefficients
t = linspace(-5,5);
poly = newton(c,x,t); % evaluate the polynomial
plot(t,[f(t);poly]); % plot function and its polynomial
hold on
plot(x,y,'ro') % also mark the interpolated values
@normalhuman
normalhuman / intpoly1.m
Last active September 18, 2015 05:09
Interpolating polynomial, Vandermonde method
x = [1 2 3 4]'; % transpose to make a column
y = [3 1 4 1]';
n = length(x); % number of elements
M = zeros(n,n); % initialize a matrix n by n
for k=1:n
M(:,k) = x.^(k-1); % fill the matrix with powers of x-values
end
coeff = M\y; % find the coefficients
t = linspace(1,4);
poly = coeff(n)*ones(size(t)); % prepare for evaluation