%Lab 2
%Written by Jeannette Spuhler, 2011-09-08
%modified 2011-11-06

%Interpolation
%LabDN1240 numo11
clear all; clc;
tidpunkter = 0:3:24;
tidpunkter = tidpunkter';
Temp = [-1.2 -4 -2.2 -2.5 -0.9 0 -1.5 -2 -5.3]';

%-------------------------------------------------------------------------------------------------------------

%interpolation with polynom of grad 8
%Ax=y
%Matrix A is called Vandermondematrix
A = [ones(size(tidpunkter)) tidpunkter tidpunkter.^2 tidpunkter.^3 tidpunkter.^4 tidpunkter.^5 tidpunkter.^6 tidpunkter.^7 tidpunkter.^8];
coeff = A\Temp;
x=0:0.01:24;
y=coeff(1)+coeff(2)*x+coeff(3)*x.^2+coeff(4)*x.^3+coeff(5)*x.^4+coeff(6)*x.^5+coeff(7)*x.^6+coeff(8)*x.^7+coeff(9)*x.^8;

%plotting
subplot(3,1,1);
plot(x,y,  tidpunkter, Temp, '*');
axis([0 24 -6 1]);
title('Lab2 -Polynominterpolation: interpolation with polynom of order 8'); 
ylabel('y');
xlabel('x');

%-------------------------------------------------------------------------------------------------------------
%styckvis linear interpolation

for i= 1:8
    A = [tidpunkter(i) 1; tidpunkter(i+1) 1];
    y = [Temp(i) ;Temp(i+1)];
    coeffs = A\y;
    x=3*(i-1):0.01:(3*i);
    f=coeffs(1)*x+coeffs(2); % f=a*x+b
    subplot(3,1,2);
    plot(x,f); hold on;
end

%plotting
plot(tidpunkter, Temp, '*');
axis([0 24 -6 1]);
title('Lab2 - Polynominterpolation: piecewise linear interpolation'); 
ylabel('y');
xlabel('x');
%the same plot can be achieved by simply writing
%plot(tidpunkter, Temp, '--g');  
%since Matlab draws a line
%between the points
hold off;



%-------------------------------------------------------------------------------------------------------------
%interpolation with the functions provided in matlab
x=0:0.01:24;
p = polyfit(tidpunkter,Temp,8); 
y = polyval(p, x);

%plotting
subplot(3,1,3);
plot(x,y, tidpunkter, Temp, '*');
axis([0 24 -6 1]);
title('Lab2 - Polynominterpolation: with polyval and polyfit'); 
ylabel('y');
xlabel('x');
