%% Exercise 5 Data fitting with outlier and sinusoid
%%
% 
%  File:Exercise5_DatafitOutlier_sinusoid.m 
%
% HA 4.12.2018

clear; close all; format compact
t = 1:25;
y = [ 5.0291  6.5099  5.3666  4.1272  4.2948 ...
      6.1261 12.5140 10.0502  9.1614  7.5677 ...
      7.2920 10.0357 11.0708 13.4045 12.8415 ...
     11.9666 11.0765 11.7774 14.5701 17.0440 ...
     17.0398 15.9069 15.4850 15.5112 17.6572];
figure(1)
plot(t,y,'o');grid on
%% Fit an LSQ-line
%%
% 
%  Can be done using *polyfit*, *polyval* as in Exercise 2.
%  Let's do it this time in a way that can be easily generalized
%  to a non-polynomil case. 
% 
% <html>
% <a href="http://math.aalto.fi/opetus/Mattie/lectures/kokoprujuCurveFitting.pdf">Lectures on CurveFitting</a>
% </html>
%
t = t';
y = y';
A = [ones(size(t)) t]; % Vandermonde matrix for fittig an LSQ-line
c = A\y;                % coeffs of poly
%%
f = A*c;               % 
hold on
plot(t,f);shg
%% The same with polyfit:
C=polyfit(t,y,1);
F=polyval(C,t);
figure
plot(t,y,'o',t,F);grid on
%%
figure(2)
clf
subplot(2,1,1)
bar(t,y-f);
title('y-f bar-plot')
grid on
subplot(2,1,2)
plot(t,y-f,'-*')
grid on
title('y-f, line-plot')
disp('(t(7),y(7)) is the outlier')
%% Data with outlier removed
%%
clf  % Clear Graphics
t7 = t(7);
y7 = y(7);
t(7) = [];   % Remove  t(7)  NOTE HOW NICE!
y(7) = [];   % ... and y(7)
plot(t,y,'*')
shg
%% Fit LSQ-line to data with outlier removed
%%
A = [ones(size(t)) t];
c=A\y;
f1=A*c;
hold on
plot(t,f1);title('Data with outlier removed');grid on;shg
% 
% Looks like sinusoidal "disturbance" of straight line.
%% Try sinusoidal fit
% Instead of monomials, our basis functions are: $1, t, \sin t$
%  The modified Vandemonde is then: 
%
A = [ones(size(t)) t sin(t)]; % (t.^2 is replaced by sin(t))
c = A\y;
%%
s = (0:.1:26)';  % Evaluation points (Not the same as datapoints)
f = [ones(size(s)) s sin(s)]*c; 
figure(3)
plot(t,y,'o',s,f,'-',t7,y7,'*')
axis tight; grid on
title('Sinusoidal fit to data with outlier removed')
legend('Data','fit','outlier','Location','NW')
%%