%% Kittiphan Techakittiroj (27 Jan 1996)

%% Input
figure(1);
k = 0:1:100;
x = [ zeros(2,1); 0.01*[1:50]'; ones(25,1); zeros(24,1)];
w = [ zeros(2,1); ones(50,1); zeros(25,1); zeros(24,1)];
xw = [x(3:length(x)); 0; 0].*w;
plot(k, xw);
title('an example input');
ylabel('Input (unit)');  xlabel('time (unit)');  grid;
input = [ xw ];

%% Model
figure(2);
B0 = [   0 ];   A0 = [    1 ];  %% delay 0
B1 = [   0 ];   A1 = [    0 ];  %% delay 1
B2 = [   0 ];   A2 = [ 0.98 ];  %% delay 2
B3 = [   5 ];                   %% delay 3
AA = [ A0 A1 A2];
BB = [ B0 B1 B2 B3];
Model = arx2th( AA, BB, 1, 1);
y = idsim(input, Model);
plot(k, y);
title('an example output from the simulation');
ylabel('Output (unit)');  xlabel('time (unit)');  grid;


%% Add noise to the output
figure(3);
y_n = y + max(y)*0.1*(randn(size(y)) - 0.5);
plot(k, y_n);
title('an example output from the simulation + noise');
ylabel('Output (unit)');  xlabel('time (unit)');  grid;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% ARX Method
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Identification
ident_data = [y input];
na = [2];
nb = [1];
nc = [3];
[I_A I_B] = th2arx(arx(ident_data, [na nb nc]));

%% Compare
I_A
I_B

%% Identification
ident_data = [y_n input];
na = [2];
nb = [1];
nc = [3];
[I_A I_B] = th2arx(arx(ident_data, [na nb nc]));

%% Compare
I_A
I_B


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% RARX Method
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lam = 0.9;

%% Identification
ident_data = [y input];
na = [2];
nb = [1];
nc = [3];
I_Model = rarx(ident_data, [na nb nc], 'ff', lam);

%% Compare
I_Model(length(ident_data),:)

%% Identification
ident_data = [y_n input];
na = [2];
nb = [1];
nc = [3];
I_Model = rarx(ident_data, [na nb nc], 'ff', lam);

%% Compare
I_Model(length(ident_data),:)
