%----------------- Interpolation and Approximation -----------------
%
% Technical University of Sofia - MUSSPI lab course
% Created by Viktor Stoev
% October 2016
%------------------------------------------------

close all;
clear all;

%% Load data, display data and plot polynomial values after calculation

A = load('PROBA32A_2.SNS');

temp = A(:,1);
res = A(:,2);

figure(1);
plot(temp,res,'r');
title('Termistor response');
xlabel('Temperature [*C]');
ylabel('Resistance');

degree = input('Enter polynomial degree: ');

[P,S] = polyfit(temp,res,degree);

figure(2);
plot(1:size(P,2),P,'x','linewidth',2);
title('Polynomial coefficients');
xlabel('Polynomial number');
ylabel('Coefficient magnitude');

%% Calculae and plot the approximating polynomial

[Y,DELTA] = polyval(P,temp,S);

figure(3);
plot(temp,Y);
hold on;
plot(temp,res,'r');
legend('Approximation','Generated');
xlabel('Temperatura [*C]');
ylabel('Resistence [Ohm]');
title('Approximation with a polynomial');

%% Plot the error 

figure(4);
plot(DELTA);
title('Error estimation');
ylabel('Error magnitude (st.dev.)');
xlabel('Estimation number');

%% Loop with 4 poly degrees

for p = 1:4
    degree_x = input(['Enter poly degree ' num2str(p) ' to compute the error for:']);
    vec_degrees(p) = degree_x;
    [coeff,struct] = polyfit(temp,res,degree_x);
    a = polyfit(temp,res,degree_x);
    [yapprox, delta] = polyval(coeff,temp,struct);
    delta_mat(:,p) = delta;
end

figure(5);
subplot(2,2,1);
plot(temp,delta_mat(:,1));
title(['Error estimation for a polynomial of degree ',num2str(vec_degrees(1))]);
ylabel('Error magnitude (st.dev.)');
xlabel('Estimation number');
subplot(2,2,2);
plot(temp,delta_mat(:,2));
title(['Error estimation for a polynomial of degree ',num2str(vec_degrees(2))]);
ylabel('Error magnitude (st.dev.)');
xlabel('Estimation number');
subplot(2,2,3);
plot(temp,delta_mat(:,3));
title(['Error estimation for a polynomial of degree ',num2str(vec_degrees(3))]);
ylabel('Error magnitude (st.dev.)');
xlabel('Estimation number');
subplot(2,2,4);
plot(temp,delta_mat(:,4));
title(['Error estimation for a polynomial of degree ',num2str(vec_degrees(4))]);
ylabel('Error magnitude (st.dev.)');
xlabel('Estimation number');