% Listing 14.1 of the book for Example 14.1
% "Principles of System Identification: Theory and Practice"

% Arun K. Tangirala
% September 04, 2015
% Freely distributed under no warranty

%% Generate data
proc_mod = idpoly([1 -0.7],[0 2],1,1,1,'Noisevariance',1);

% Input design
uk = idinput(2046,'prbs',[0 0.4],[-1 1]);

% Measurement with SNR approx 10
ykstar = sim(proc_mod,uk);
proc_mod.Noisevariance = (1 - 0.49)*var(ykstar)/10;
yk = sim(proc_mod,uk,'Noise');

%% Estimate using MoM
[sigma_mat,lags] = xcov([-yk uk],1,'biased');
cov_mat = reshape(sigma_mat(2,:),2,2); 
cov_rhs = sigma_mat(3,1:2)'; 

%% Use pseudo-inverse or backslash
theta_mom = pinv(cov_mat)*cov_rhs;