% losn_oppg12.m
% L O E S N I N G S  F O R S L A G  T I L  OPPGAVE 12 %%%%%%%%%%%%%%
%
load uov8.dat
load yov8.dat

u=uov8; y=yov8; 
clear uov8 yov8
[N,r]=size(u);

%a)%%%%%%%%%%%%%%%%%%%%%%% D S R %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for L=1:5                                           
 [a,b,d,e,c,f,x0]=dsr(y,u,L,1,L,1,1);
 a_dsr(L,1)=a; b_dsr(L,1)=d*b; d_dsr(L,1)=1; e_dsr(L,1)=e; 
 c_dsr(L,1)=d*c*inv(f); x0_dsr(L,1)=x0;
 hd_dsr(L,1)=ddcgain(a,b,d,e);
end
ym_dsr=dlsim(a_dsr(1),b_dsr(1),d_dsr(1),e_dsr(1),u,x0_dsr(1));

%b)%%%%%%%%%%%%%%%%%%%%%%% P C R %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hd=y'*u*pinv(u'*u);                                 % Least Squares
ym_pcr = hd*u;

%c)%%%%%%%%%%%%%%%%%%%%%%% A R X %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
th_arx=arx([y u],[1,2,0]);
[a_arx,b_arx,d_arx,e_arx,c_arx]=th2ss(th_arx);
ym_arx=dlsim(a_arx,b_arx,d_arx,e_arx,u);
hd_arx=ddcgain(a_arx,b_arx,d_arx,e_arx);

%d)%%%%%%%%%%%%%%%%%%%%%%% A R M A X %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
th_armax=armax([y u],[1,2,1,0]);
[a_armax,b_armax,d_armax,e_armax,c_armax]=th2ss(th_armax);
ym_armax=dlsim(a_armax,b_armax,d_armax,e_armax,u);
hd_armax=ddcgain(a_armax,b_armax,d_armax,e_armax);

%e)%%%%%%%%%%%%%%%%%%%%%%% P E M %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ms=canform(1,1,[1,1,1]);                            % Modellstructur
th0=ms2th(ms);                                      % Transform til theta form.
th_pem=pem([y u],th0);                              % Id. parametre.
[a_pem,b_pem,d_pem,e_pem,c_pem,x0_pem]=th2ss(th_pem);                
ym_pem=dlsim(a_pem,b_pem,d_pem,e_pem,u,x0_pem);
hd_pem=ddcgain(a_pem,b_pem,d_pem,e_pem);
% or as follows, for siso systems.
% po=[na nb nc nd nf nk]=[1 2 1 0 0 0]; th=pem([y u],po);

%%%%%%%%%%%%%%%%%%%%%%%%%% O E %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
th_oe=oe([y u],[2,1,0]);
[a_oe,b_oe,d_oe,e_oe,c_oe,x0_oe]=th2ss(th_oe);
hd_oe=ddcgain(a_oe,b_oe,d_oe,e_oe);


% KOMMENTARER
% -DSR OG PEM er generelle metoder, dvs. hele Kalman-filteret estimeres.
% -ARMAX identifiserer ogsaa et fullstendig Kalman-filter, men denne
%  virker bare for SISO systemer. For et SISO system kan ARMAX med fordel
%  benyttes i stedet for PEM.
% -ARX og OE er kan ikke estimere hele Kalman-filteret.
% -Parametrene i en ARX modell kan identifiseres direkte vha minste
%  kvadraters metode.
