load co2.dat

figure
plot(co2)

%observationer (som column)
y = co2(:);
%tidsvektor (som column)
t = (1:length(co2))';

%% enkel linjär regression
X1 = [ones(size(t)) t];
beta1 = X1\y %eller regress(y,X)
subplot(211)
plot(t, co2, '.-', t, X1*beta1, '-')
axis tight
subplot(212)
plot(t, co2-X1*beta1, '.')
axis tight

%% Andra ordnings polynom
X2 = [ones(size(t)) t t.^2];
beta2 = X2\y %eller regress(y,X)
subplot(211)
plot(t, co2, '.-', t, X1*beta1, '-', t, X2*beta2, '-')
axis tight
subplot(212)
plot(t, co2-X2*beta2, '.')
axis tight

%% Addera ens sinus+cosinus term
%A*sin(t + delta) = B*sin(t) + C*cos(t)
%12 månaders periodicitet
X3 = [ones(size(t)) t t.^2 sin(2*pi*t/12) cos(2*pi*t/12)];
beta3 = X3\y %eller regress(y,X)
subplot(211)
plot(t, co2, '.-', t, X1*beta1, '-', t, X2*beta2, '-', t, X3*beta3, '-')
axis tight
subplot(212)
plot(t, co2-X3*beta3, '.')
axis tight

