Download as pdf or txt
Download as pdf or txt
You are on page 1of 148

#UUR

# RTTCCEEVVKKEEGGÉÉP
RGGEEVVGGR P
/Q
/ QF FGGP
FGGNNCCTTGGCCĩĩKK++F 5KKUUVVGGO
PVVKKHHKKEECCTTGGCC5 QTT
OGGNNQ

¾ #WVQTK &CPĨVGHâPQKW+QP/CVGK2GVTG5VQKEC
E-mail: danny@router.indinf.pub.ro,
ion_matei_ro@yahoo.com,
ps@SysCon.uu.se

Documentaţia înregistrată pe Discul Compact


0QVâKO RQTVCPVâ
Ŗ ¡P XGFGTGC CHKĩâTKK ITCHKEG ÉP HGTGUVTG EW KPFGZ EQPVTQNCV FG WVKNK\CVQT OKPK
UKOWNCVQCTGNG FGLC RTQKGEVCVG QRGTGC\â EW XCTKCDKNC INQDCNâ FIG ECTG
VTGDWKGKPKįKCNK\CVâÉPCKPVGFGTWNCTGFKPOGFKWN/#6.#$CUVHGN
>> global FIG ; % Declaraţie variabilă globală.
>> FIG = n ; % Iniţializare (cu n dorit, e.g. 1).
%WRTKPU

 %CTCEVGTK\âTKÉPVKORĩKHTGEXGPįâCNGRTQEGUGNQTUVQECUVKEG
ISLAB_1A
OKPKUKOWNCVQT  %&
ISLAB_1B
OKPKUKOWNCVQT  %&
NOISE
TWVKPâCWZKNKCTâ  %&
D_SPEKTR
TWVKPâCWZKNKCTâ  %&
SPEFAC
TWVKPâCWZKNKCTâ  %&
 +FGPVKHKECTGCOQFGNGNQTPGRCTCOGVTKEG
ISLAB_2A
OKPKUKOWNCVQT  %&
ISLAB_2D
OKPKUKOWNCVQT  %&
ISLAB_2L
OKPKUKOWNCVQT  %&
 +FGPVKHKECTGRCTCOGVTKEâRTKP/GVQFC%GNQT/CK/KEK2âVTCVG
ISLAB_3D
OKPKUKOWNCVQT  %&
 +FGPVKHKECTGRCTCOGVTKEâRTKP/GVQFC8CTKCDKNGNQT+PUVTWOGPVCNG
ISLAB_4A
OKPKUKOWNCVQT  %&
F_TEST2
TWVKPâCWZKNKCTâ  %&
GAIC_R2
TWVKPâCWZKNKCTâ  %&
GENDATA
TWVKPâCWZKNKCTâ  %&
VALID_LS
TWVKPâCWZKNKCTâ  %&
 +FGPVKHKECTGRCTCOGVTKEâ
RTKP/GVQFC/KPKOK\âTKK'TQTKKFG2TGFKEįKG
ISLAB_5A
OKPKUKOWNCVQT  %&
GAIC_R3
TWVKPâCWZKNKCTâ  %&
GEN_DATA
TWVKPâCWZKNKCTâ  %&
 +FGPVKHKECTGTGEWTUKXâ
ISLAB_6A
OKPKUKOWNCVQT  %&
GDATA_VP
TWVKPâCWZKNKCTâ  %&
RIV
TWVKPâCWZKNKCTâ  %&
 #RNKECįKKFGKFGPVKHKECTGTGEWTUKXâ
ISLAB_7A
OKPKUKOWNCVQT  %&
ISLAB_7C
OKPKUKOWNCVQT  %&
ISLAB_7E
OKPKUKOWNCVQT  %&
GDATA_FP
TWVKPâCWZKNKCTâ  %&
GDATA_CP
TWVKPâCWZKNKCTâ  %&
4WVKPG/CVNCDFGW\IGPGTCN %&
..KKUUVVKKPPIIWWTTKKCCNNGGWWPPQQTTO
OKKPPKKUUKKO
OWWNNCCVVQQCCTTGG
ĩĩKKTTWWVVKKPPGGCCWWZZKKNNKKCCTTGG/
/##66..##$$ÉÉPPTTGGIIKKUUVVTTCCVVGGRRGG&
&KKUUEEWWNN%
%QQO
ORRCCEEVV
%
%CCRRKKVVQQNNWWNN
% ISLAB_1A Module that computes and displays true and estimated
% covariance functions of an ARMA[1,1] process: Ay=Ce.
%
function islab_1a(C,A,N,tau_max,nr)
%
% Inputs: C # MA polynomial (vector [1 c])
% A # AR polynomial (vector [1 a])
% N # number of data (100, by default)
% tau_max # maximum time shift (50, by default)
% nr # number of realizations (1, by default)
%
% Outputs: ---------
%
% Explanation: The number of data N used in the estimation
% and the maximum time shift tau_max can also
% be used to study the effect of the individual
% realizations by repeating the estimation
% procedure nr times.
%
% Author: Helena Haglund (*)
% Revised: Bjorn Wittenmark (*)
% Dan Stefanoiu (**)
% Last upgrade: (*) January 3, 1997
% (**) December 16, 2003
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Dept. of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Setting the defaults


% ~~~~~~~~~~~~~~~~~~~~
clf
lam=1;
if nargin<5
nr=1;
end;
if isempty(nr)
nr=1;
end;
if nargin<4
tau_max=50;
end;
if isempty(tau_max)
tau_max=50;
end;
if nargin<3
N=100;
end;
if isempty(N)
N=100;
end;
if nargin<2
C=1;
end;
if isempty(C)
C=1;
end;
if nargin<1
A=1;
end;
if isempty(A)
A=1;
end;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if length(A)<2
a=0;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

else
a=A(2);
end;
if length(C)<2
c=0;
else
c=C(2);
end;
%
% Computing the estimated response
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tau=[1:tau_max]';
tau_vec=[0;tau];
e=randn(N,nr);
sys= filt(C,A,1);
for n=1:nr
yn=lsim(sys,e(:,n));
[tmp,lags]=xcov(yn,tau_max,'unbiased');
r_e(:,n)=tmp(tau_max+1:end);
end;
%
% Computing the true response
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~
r_t=lam/(1-a^2)*[(1+c^2-2*a*c); ...
(c-a)*(1-a*c)*(-a).^(tau-1)];
%
% Plotting
% ~~~~~~~~
NN=min(N,50);
m=mean(r_e')';
st=std(r_e')';
subplot(211)
plot(tau_vec,r_t,'r-',tau_vec,r_e,'b--');
hold on;
legend('True','Estimated');
title(['Covariance functions']);
xlabel('k');
subplot(212)
plot(yn(1:NN));

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

grid;
title(['Realization (',num2str(NN),' samples)']);
xlabel('Discrete time');
%
% END
%
% ISLAB_1B Module that simulates how an ARMA[2,2] model
% equivalent to an AR[2] model plus a second noise
% (see Exercise #4) varies with the SNR
% (signal-to-noise ratio).
%
function islab_1b(x,y,SNR)
%
% Inputs: x # real part of poles for AR model
% (0.5, by default)
% y # imaginary part of poles for AR model
% (0.5, by default)
% SNR # given SNR (3, by default)
%
% Outputs: ---------
%
% Explanation: An AR(2) process, with poles specified by
% real part x and imaginary part y, is observed
% in white measurement noise. The AR(2) process
% has poles in x+iy and x-iy. The disturbed output
% signal can be viewed as generated by an
% ARMA(2,2) process. The function shows how
% the poles and zeros of the ARMA process are
% varying with the SNR.
%
% Author: Helena Haglund (*)
% Revised: Bjorn Wittenmark (*)
% Dan Stefanoiu (**)
% Last upgrade: (*) January 3, 1997
% (**) December 16, 2003
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Dept. of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% BEGIN
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
clf
if nargin<3
SNR = 3;
end;
if isempty(SNR)
SNR = 3;
end;
if nargin<2
y = 0.5;
end;
if isempty(y)
y = 0.5;
end;
if nargin<1
x = 0.5;
end;
if isempty(x)
x = 0.5;
end;
%
% Deriving the equivalent MA polynomial
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a1=-2*x;
a2=x^2+y^2;
A=[1 a1 a2];
lv2=1;
%
% Determine le2 (lambda_e^2)
%
Rx=[1 a1 a2;a1 1+a2 0;a2 a1 1]\[lv2;0;0];
le2=Rx(1)/SNR;
%
% Spectral factorization
%
r0=lv2+le2*( 1+a1^2+a2^2 );

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

r1=le2*( a1+a1*a2 );
r2=le2*a2;
R=[r0 r1 r2];
[D,leps2]=spefac(R);
poler=roots(A);
nollst=roots(D);
%
% Plotting the poles and zeros
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
subplot(211)
tt=0:.1:6.3; % Plot the unit circle
plot(sin(tt),cos(tt),'k-');
hold on;
axis('square')
set(gca,'xtick',[-1 -0.5 0 0.5 1]);
set(gca,'ytick',[-1 -0.5 0 0.5 1]);
% Show the poles.
plot(real(poler),imag(poler),'rx');
hold on;
% Show the zeros.
plot(real(nollst),imag(nollst),'ro');
axis('square')
grid on;
title('Poles (x) and zeros (o)')
%
% Evaluating the spectrum
% ~~~~~~~~~~~~~~~~~~~~~~~
% AR spectrum
[w_AR,fi_AR]=d_spektr(A,1,lv2);
%
% Noise spectral estimation
w_NOISE=w_AR;
[slask1,slask2]=size(fi_AR);
fi_NOISE=le2*ones(slask1,slask2)/(2*pi);
%
% ARMA spectrum
[w_ARMA,fi_ARMA]=d_spektr(A,D,leps2);

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Plotting spectra
% ~~~~~~~~~~~~~~~~
subplot(212)
loglog(w_AR,fi_AR,w_NOISE,fi_NOISE,w_ARMA,fi_ARMA);
legend('AR','White noise','ARMA')
grid on;
title('Spectral densities');
xlabel('\omega');
%
% END
%
%
% NOISE Module illustrating stochastic processes.
%
function noise(operation)
%
% Inputs: operation
% # character string in range:
% 'close_noise'
% 'close_noise_def'
% 'init_noise'
% 'move_p'
% 'move_z'
% 'moved_p'
% 'moved_z'
% 'moving_p'
% 'moving_z'
% 'noiseclear'
% 'show' (by default)
% 'system'
% 'winit_noise'
%
% Outputs: -----------
%
% Author: Helena Haglund (*)
% Revised: Bjorn Wittenmark (*)
% Dan Stefanoiu (**)
% Last upgrade: (*) January 3, 1997
% (**) December 16, 2003

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Copyright: (*) Lund Institute of Technology, SWEDEN


% Dept. of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Global variables
% ~~~~~~~~~~~~~~~~
global fig_noise fig2_noise ccs_col fig_ccs
global system_noise error_noise
global Bd Ad h
global pole zero x y
global disc_axes_noise
global lgw1 lgw2 n w i tau wvec t
global ry C fr e
global a1 a2 b1 Bd1 K
global cov_handle spectr_handle realiz_handle
global cov_axes spectrum_axes realization_axes
%
% Initial constants
% ~~~~~~~~~~~~~~~~~
ccs_col=1;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin<1),
operation = 'show';
end;
if (isempty(operation))
operation = 'show';
end;
%
% Operation: SHOW
% ~~~~~~~~~~~~~~~
%
% - checks if window already exists
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if strcmp(operation,'show')
[existFlag,figNumber]=figflag('Noise');
if ~existFlag
noise('winit_noise');
noise('init_noise');
[existFlag,figNumber]=figflag('Noise');
else
clf;
noise('init_noise');
end;
%
% Operation: SYSTEM
% ~~~~~~~~~~~~~~~~~
%
% - otherwise, draw the window
%
elseif strcmp(operation,'system')
watchon;
figure(fig_noise);
set(error_noise,'Visible','off');
h = 1;
%
% - make plots go clear after next updating
%
set(cov_handle,'EraseMode','XOR');
set(spectr_handle,'EraseMode','XOR');
set(realiz_handle,'EraseMode','XOR');
if get(system_noise,'value')==1
axes(disc_axes_noise);
cla;
%
% - plot unit circle
%
t=0:.1:6.3;
plot(sin(t),cos(t),'k-');
axes(cov_axes);
cla;
axes(spectrum_axes);
cla;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

axes(realization_axes);
cla;
elseif get(system_noise,'value')==2
Ad = [1 -0.5];
a1 = -0.5;
%
% - gives var(y)=1
%
Bd_test = 0;
Bd1 = 1;
Bd = sqrt(1-a1^2);
[phi,gam,C,D] = tf2ss(Bd,Ad);
elseif get(system_noise,'Value')==3,
Ad = [1 -0.3 0.1];
Bd1 = [1 -0.5];
a1 = -0.3;
a2 = 0.1;
b1 = -0.5;
%
% - gives var(y)=1
%
Bd_test = 0;
vary = ((1+b1^2)*(1+a2)-2*b1*a1)/...
((1-a2^2)*(1+a2)-(a1-a1*a2)*a1);
K = 1/sqrt(vary);
Bd = K*Bd1;
[phi,gam,C,D] = tf2ss(Bd,Ad);
end;
if get(system_noise,'Value')==2 | ...
get(system_noise,'Value')==3 | ...
get(system_noise,'Value')==4
axes(disc_axes_noise);
cla;
%
% - plot unit circle
%
t=0:.1:6.3;
plot(sin(t),cos(t),'k-');

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% - plot poles and zeros of sampled system


%
if ccs_col==1
pole = plot(real(roots(Ad)),imag(roots(Ad)),'rx');
set(pole,'Linewidth',2,'EraseMode','XOR', ...
'Markersize',10);
zero = plot(real(roots(Bd)),imag(roots(Bd)),'ro');
set(zero,'Linewidth',2,'EraseMode','XOR',...
'Markersize',7);
else
pole = plot(real(roots(Ad)),imag(roots(Ad)),'kx');
set(pole,'Linewidth',2,'EraseMode','XOR', ...
'Markersize',10);
zero = plot(real(roots(Bd)),imag(roots(Bd)),'ko');
set(zero,'Linewidth',2,'EraseMode','XOR',...
'Markersize',7);
end;
%
% - makes poles movable
%
set(pole,'ButtonDownFcn','noise(''move_p'')');
set(zero,'ButtonDownFcn','noise(''move_z'')');
%
% - calculates covariance function
%
ry = zeros(20,1);
tau = 20;
rx = dlyap(phi,gam*gam');
ry(1) = C*rx*C';
for k=1:tau
rx = phi*rx;
ry(k+1) = C*rx*C';
end;
axes(cov_axes);
%
% - plot covariance function
%
set(cov_handle,'XData',0:tau,'YData',ry);
set(cov_handle,'LineWidth',2,'EraseMode','None');

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% - calculate spectrum
%
[w_ab,fi_ab]=d_spektr(Ad,Bd,1);
%
% - plot spectrum
%
axes(spectrum_axes);
set(spectr_handle,'XData',w_ab,'YData',fi_ab);
set(spectr_handle,'LineWidth',2,'EraseMode','None');
%
% - calculate realization
%
axes(realization_axes);
%
% - white noise
%
e = randn(1,50);
y = filter(Bd,Ad,e);
t = 0:49;
%
% - plot realization
%
set(realiz_handle,'XData',t,'YData',y);
set(realiz_handle,'LineWidth',2,'EraseMode','None');
end;
axes(disc_axes_noise);
figure(fig_noise);
watchoff;
%
% Operation: MOVE_P, MOVED_P, MOVING_P (poles)
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(operation,'move_p')
set(fig_noise,'WindowButtonMotionFcn', ...
'noise(''moving_p'');', ...
'WindowButtonUpFcn', ...
'noise(''moved_p'');');
elseif strcmp(operation,'moving_p')
currpoint = get(disc_axes_noise,'CurrentPoint');
x = currpoint(1,1);

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

y = currpoint(1,2);
if get(system_noise,'Value')==2
if ccs_col==1
set(pole,'XData',x,'YData',0,'Color','r');
else
set(pole,'XData',x,'YData',0,'Color','k');
end;
elseif get(system_noise,'Value')==3
if ccs_col==1
set(pole,'XData',[x x],'YData',[y -y],'Color','r');
else
set(pole,'XData',[x x],'YData',[y -y],'Color','k');
end;
end;
elseif strcmp(operation,'moved_p')
%
% - update plots after completed move
%
if get(system_noise,'Value')==2
if ccs_col==1
set(pole,'XData',x,'YData',0,'Color','r');
else
set(pole,'XData',x,'YData',0,'Color','k');
end;
Ad = [1 -x];
a1 = -x;
%
% - test stability
%
if (abs(x)>=1)
Bd_test = 1;
Bd = Bd1;
else
%
% - gives var(y)=1
%
Bd_test = 0;
Bd=sqrt(3)/2;
end;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

elseif get(system_noise,'Value')==3
if ccs_col==1
set(pole,'XData',[x x],'YData',[y -y],'Color','r');
else
set(pole,'XData',[x x],'YData',[y -y],'Color','k');
end;
Ad = [1 -2*x x^2+y^2];
a1 = -2*x;
a2 = x^2+y^2;
%
% - test stability
%
if (max(abs(roots(Ad)))>=1)
Bd_test = 1;
Bd = Bd1;
else
Bd_test = 0;
%
% - gives var(y)=1
%
vary = ((1+b1^2)*(1+a2)-2*b1*a1)/ ...
((1-a2^2)*(1+a2)-(a1-a1*a2)*a1);
K = 1/sqrt(vary);
Bd = K*Bd1;
end;
[phi,gam,C,D] = tf2ss(Bd,Ad);
end;
%
% - warning message if system is unstable
%
if (Bd_test==1 & get(system_noise,'Value')==2) | ...
(Bd_test==1 & get(system_noise,'Value')==3)
set(error_noise,'Visible','on');
else
set(error_noise,'Visible','off');
end;
[phi,gam,C,D] = tf2ss(Bd,Ad);
set(fig_noise,'WindowButtonMotionFcn','', ...
'WindowButtonUpFcn','');

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% - covariance function and spectrum if system is stable


%
if Bd_test==0
%
% - calculate covariance function
%
rx = dlyap(phi,gam*gam');
ry(1) = C*rx*C';
for k=1:tau
rx = phi*rx;
ry(k+1) = C*rx*C';
end;
%
% - plot covariance function
%
axes(cov_axes);
set(cov_handle,'XData',0:tau,'YData',ry);
%
% - calculate spectrum
%
[w_ab,fi_ab]=d_spektr(Ad,Bd,1);
%
% - plot spectrum
%
axes(spectrum_axes);
set(spectr_handle,'XData',w_ab,'YData',fi_ab);
set(spectr_handle,'LineWidth',2,'EraseMode','None');
end;
%
% - calculate and plot realization
%
axes(realization_axes);
y = filter(Bd,Ad,e);
t=0:49;
set(realiz_handle,'XData',t,'YData',y);
axes(disc_axes_noise);
figure(fig_noise);
watchoff;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Operation: MOVE_Z, MOVED_Z, MOVING_Z (zeros)


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(operation,'move_z')
set(fig_noise,'WindowButtonMotionFcn', ...
'noise(''moving_z'');', ...
'WindowButtonUpFcn', ...
'noise(''moved_z'');');
elseif strcmp(operation,'moving_z')
currpoint = get(disc_axes_noise,'CurrentPoint');
x = currpoint(1,1);
y = currpoint(1,2);
set(zero,'XData',x,'YData',0);
elseif strcmp(operation,'moved_z')
%
% - update plots after completed move
%
watchon;
set(zero,'XData',x,'YData',0);
Bd1 = [1 -x];
b1 = -x;
%
% - test stability
%
if (max(abs(roots(Ad)))>=1)
Bd_test = 1;
Bd = Bd1;
else
Bd_test = 0;
%
% - gives var(y)=1
%
vary = ((1+b1^2)*(1+a2)-2*b1*a1)/ ...
((1-a2^2)*(1+a2)-(a1-a1*a2)*a1);
K = 1/sqrt(vary);
Bd = K*Bd1;
end;
[phi,gam,C,D] = tf2ss(Bd,Ad);
set(fig_noise,'WindowButtonMotionFcn','', ...
'WindowButtonUpFcn','');

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% - covariance function and spectrum if system is stable


%
if Bd_test==0
%
% - calculate covariance function
%
rx = dlyap(phi,gam*gam');
ry(1) = C*rx*C';
for k=1:tau
rx = phi*rx;
ry(k+1) = C*rx*C';
end;
%
% - plot covariance function
%
axes(cov_axes);
set(cov_handle,'XData',0:tau,'YData',ry);
%
% - calculate spectrum
%
[w_ab,fi_ab]=d_spektr(Ad,Bd,1);
%
% - plot spectrum
%
axes(spectrum_axes);
set(spectr_handle,'XData',w_ab,'YData',fi_ab);
set(spectr_handle,'LineWidth',2,'EraseMode','None');
end;
%
% - calculate and plot realization
%
axes(realization_axes);
y = filter(Bd,Ad,e);
t=0:49;
set(realiz_handle,'XData',t,'YData',y);
axes(disc_axes_noise);
figure(fig_noise);
watchoff;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Operation: NOISECLEAR
% ~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(operation,'noiseclear')
if get(system_noise,'Value')==2 | ...
get(system_noise,'Value')==3 | ...
get(system_noise,'Value')==4
%
% - plot the most recent covariance function
%
axes(cov_axes);
cla;
if ccs_col==1
cov_handle = plot(0:tau, ry,'r');
else
cov_handle = plot(0:tau, ry,'k');
end;
set(cov_handle,'LineWidth',2,'EraseMode','None');
%
% - plot the most recent spectrum
%
axes(spectrum_axes);
cla;
if ccs_col==1
spectr_handle = loglog(w_ab,fi_ab,'r');
else
spectr_handle = loglog(w_ab,fi_ab,'k');
end;
set(spectr_handle,'LineWidth',2,'EraseMode','None');
%
% - plot the most recent realization
%
axes(realization_axes);
cla;
if ccs_col==1
realiz_handle = plot(t,y,'r');
else
realiz_handle = plot(t,y,'k');
end;
set(realiz_handle,'LineWidth',2,'EraseMode','None');

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

figure(fig_noise);
axes(disc_axes_noise);
end;
%
% Operation: WINIT_NOISE
% ~~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(operation,'winit_noise')
%
% - create main window
%
fig_noise = figure('Name','Noise','NumberTitle','off', ...
'Units','Normalized','Position', ...
[0.2561 0.4400 0.4861 0.4667 ], ...
'BackingStore','Off',...
'DefaultUicontrolFontSize',11);
set(fig_noise,'Color',[0.8 0.8 0.8]);
%
% Operation: INIT_NOISE
% ~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(operation,'init_noise')
watchon;
figure(fig_noise);
%
% - frame left
%
close_noise = ...
uicontrol(fig_noise,'Style','Push', ...
'String','Quit', ...
'Units','Normalized', ...
'Position', ...
[0.0339 0.0690 0.1429 0.0595 ], ...
'BackgroundColor',[1 0.4 0.4], ...
'Callback', ...
'noise(''close_noise_def'');');
%
% - frame middle
%
frame_middle = ...
uicontrol(fig_noise,'Style','Frame', ...

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

'Units','Normalized', ...
'Position', ...
[0.2036 0.7119 0.3214 0.2619 ]);
system_noise = ...
uicontrol(fig_noise,'Style','popup', ...
'Units','Normalized', ...
'Position', ...
[0.2214 0.8667 0.2857 0.0595 ], ...
'string',...
['Select system | ' ...
'b/(z+a) | ' ...
'(b0z+b1)/(z^2+a1*z+a2)']);
set(system_noise,'Callback','noise(''system'');');
%
% - create pole/zero axes
%
disc_axes_noise = axes('position',[0.23 0.15 0.28 0.28]);
%
% - plot unit circle
%
t=0:.1:6.3;
plot(sin(t),cos(t),'k-');
grid on;
axis('equal');
title('Poles/Zeros','Color','k', ...
'FontName','Times','Fontsize',11);
set(disc_axes_noise,'XLim',[-1.05 1.05], ...
'YLim',[-1.05 1.05], ...
'Clipping','Off', ...
'XLimMode','Manual', ...
'YLimMode','Manual', ...
'YTick',[-1 0 1], ...
'DrawMode','Fast','Xcolor','k', ...
'Ycolor','k', ...
'FontName','Times','Fontsize',11);
hold on;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% - create covariance diagram


%
cov_axes = axes('Position',[0.6 0.71 0.35 0.22]);
grid on;
set(cov_axes,'XLim',[0 20],'YLim',[-1 2], ...
'DrawMode','Fast','Clipping','Off', ...
'XLimMode','Manual','YLimMode','Manual', ...
'XColor','k','YColor','k', ...
'FontName','Times','Fontsize',11);
title('Covariance function','Color','k', ...
'FontName','Times','Fontsize',11);
hold on;
%
% - create spectrum diagram
%
spectrum_axes = axes('Position',[0.6 0.39 0.35 0.22]);
grid on;
set(spectrum_axes,'XLim',[0.01 4],'YLim',[0.01 5], ...
'XScale','log','YScale','log', ...
'XColor','k','YColor','k', ...
'FontName','Times','Fontsize',11);
title('Spectrum','Color','k',...
'FontName','Times','Fontsize',11);
hold on;
%
% - create realization diagram
%
realization_axes = axes('Position',[0.6 0.05 0.35 0.22]);
grid on;
set(realization_axes,'XLim',[0 50],'YLim', [-5 5], ...
'DrawMode','Fast','Clipping','Off', ...
'XLimMode','Manual', ...
'YLimMode','Manual', ...
'XColor','k','YColor','k', ...
'FontName','Times','Fontsize',11);
title('Realization','Color','k', ...
'FontName','Times','Fontsize',11);
hold on;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% - create handles
%
axes(cov_axes);
if ccs_col==1
cov_handle = plot(NaN,NaN,'r');
axes(spectrum_axes);
spectr_handle = loglog(NaN,NaN,'r');
axes(realization_axes);
realiz_handle = plot(NaN,NaN,'r');
else
cov_handle = plot(NaN,NaN,'k');
axes(spectrum_axes);
spectr_handle = loglog(NaN,NaN,'k');
axes(realization_axes);
realiz_handle = plot(NaN,NaN,'k');
end;
watchoff;
%
% - error mesage
%
error_noise = ...
uicontrol(fig_noise,'Style','text',...
'Units', 'Normalized', ...
'Position', ...
[0.2304 0.5202 0.2679 0.0950 ], ...
'String','Unstable system!', ...
'Fontsize',12, ...
'BackgroundColor','r');
set(error_noise,'Visible','off');
%
% Operation: CLOSE_NOISE
% ~~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(operation, 'close_noise')
[existFlag,figNumber]=figflag('Noise');
if existFlag
close(fig_noise);
end;
[existFlag,figNumber]= ...
figflag('Sampled Data Systems Help');

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if existFlag
close;
end;
[existFlag,figNumber]= ...
figflag('Welcome to Sampled Data Systems Demo!');
if existFlag
set(fig_ccs,'Visible','on');
end;
%
% Operation: CLOSE_NOISE_DEF
% ~~~~~~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(operation, 'close_noise_def')
[existFlag,figNumber]=figflag('Noise');
if existFlag
close(fig_noise);
end;
[existFlag,figNumber]= ...
figflag('Sampled Data Systems Help');
if existFlag
close;
end;
[existFlag,figNumber]= ...
figflag('Welcome to Sampled Data Systems Demo!');
if existFlag
close(fig_ccs);
end;
%
% Operation: unknown
% ~~~~~~~~~~~~~~~~~~
else
error(['### Unknown argument <<' ...
operation '>>. Nothing to do.']) ;
end;
%
% END
%

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% D_SPEKTR Evaluates the spectral density of linear systems


% (filters) output when stimulated by the
% white noise.
%
function [w,fi]=d_spektrum(A,B,sigma2)
%
% Inputs: A # transfer function denominator (polynomial)
% B # transfer function numerator (polynomial)
% sigma2 # white noise variance
%
% Outputs: w # omega (pulsation axis)
% fi # spectral density of filter output
%
% Author: Helena Haglund (*)
% Revised: Bjorn Wittenmark (*)
% Dan Stefanoiu (**)
% Last upgrade: (*) January 3, 1997
% (**) December 16, 2003
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Dept. of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
lgw1=-2;
w=logspace(lgw1,pi)';
Hp=freqz(B,A,w);
wm=-w;
Hm=freqz(B,A,wm);
fi=sigma2*(Hp.*Hm)/(2*pi);
%
% END
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% SPEFAC Spectral factorization.


%
function [a,l2]=spefac(r)
%
% Inputs: r # auto-covariance sequence (vector)
%
% Outputs: a # coefficients of spectral factor
% (AR model - vector)
% l2 # variance of AR model
% Explanation: Given the sequence r(0) ... r(n),
% compute the sequence of coefficients
% a(1) ... a(n) and the variance l2 such that:
% l2*[z^n + a1*z^(n-1) + ... + a(n)]*
% [z^(-n) + a1*z^(1-n) + ... + a(n)] =
% = r(0)+r(1)*[z+z^(-1)]+...+r(n)*[z^(n)+z^(-n)].
%
% Note: The sequence r is assumed to be positively definite.
%
% Author: Helena Haglund (*)
% Revised: Bjorn Wittenmark (*)
% Dan Stefanoiu (**)
% Last upgrade: (*) January 3, 1997
% (**) December 16, 2003
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Dept. of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
if r(1)<max(abs(r))
error('### r is not positive definite') ;
return;
end;
[n,n2]=size(r);
if n<n2
n=n2;
r=r';
end;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

a=r'/sqrt(r(1));
da=1;
k=0;
while da>1e-14
k=k+1;
for i=1:n
aa(i,:)=[a(i:n),zeros(1,i-1)]+ ...
[zeros(1,i-1),a(1:n+1-i)];
end;
x=2*(aa\r);
a1=(a+x')/2;
da=norm(a1-a);
a=a1;
if k==50
error('### Convergence too slow.');
return;
end;
end;
l2=a(1)^2;
a = a/a(1);
%
% END
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

%
%CCRRKKVVQQNNWWNN
% ISLAB_2A Module that estimates the step response of an
% ARX[1,1] model.
%
function [yi,y] = islab_2a(a,b,delay,N,nr)
%
% Inputs: a # coefficient of AR part (-0.8, by default)
% b # coefficent of X part (1, by default)
% delay # delay of unit step (9, by default)
% N # simulation period (100, by default)
% nr # number of realizations (100, by default)
%
% Outputs: yi # ideal output of model (noise free)
% (N-length column vector)
% y # collection of all nr realisations
% (N-by-nr matrix)
%
% Explanation: The step response of an ARX[1,1] model is
% corrupted by a Gaussian white noise with unit
% variance. This simulator shows the ideal
% step response (noise free) and the averaged
% step response over nr realisations in order to
% perform the transient analysis.
%
% Author: Helena Haglund (*)
% Bjorn Wittenmark (*)
% Revised: Dan Stefanoiu (**)
% Last upgrade: (*) January 5, 1997
% (**) February 24, 2004
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Department of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
global FIG ; % Figure number handler
% (to be set before running the routine).

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Constants
% ~~~~~~~~~
lambda = 1 ; % Variance of white noise (lambda).
u0 = 1 ; % Ampitude of input step.
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 5)
nr = 100 ;
end ;
if (isempty(nr))
nr = 100 ;
end ;
nr = abs(fix(nr(1))) ;
if (~nr)
nr = 100 ;
end ;
if (nargin < 4)
N = 100 ;
end ;
if (isempty(N))
N = 100 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 100 ;
end ;
if (nargin < 3)
delay = 9 ;
end ;
if (isempty(delay))
delay = 9 ;
end ;
delay = abs(fix(delay(1))) ;
if (~delay)
delay = 9 ;
end ;
if (N < (delay+1))
N = delay + 91 ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (nargin < 2)
b = 1 ;
end ;
if (isempty(b))
b = 1 ;
end ;
b = b(1) ;
if (nargin < 1)
a = -0.8 ;
end;
if (isempty(a))
a = -0.8 ;
end;
a = a(1) ;
if (abs(a)>=1)
war_err(['<ISLAB_2A>: Model unstable. ' ...
'Reciprocal model considered instead.']) ;
a = 1/a ;
end ;
%
% Generating the Gaussian white noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambda*randn(N,nr) ;
e(1:delay,:) = e(1:delay,:)/10 ;
%
% Generating the step input
% ~~~~~~~~~~~~~~~~~~~~~~~~~
u = u0*[zeros(delay,1) ; ones(N-delay,1)] ;
%
% Generating the ideal step response
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
yi = filter([0 b],[1 a],u) ;
%
% Generating the nr realizations
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
y = yi*ones(1,N) + filter(1,[1 a],e) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Evaluating the statistic average


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ym = mean(y')' ;
%
% Evaluating the standard deviation
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ystd = std(y',1)' ;
%
% Plotting
% ~~~~~~~~
figure(FIG),clf ;
fig_look(FIG,2) ;
subplot(211) ;
m = min(min(yi),min(y(:,1))) ;
M = max(max(yi),max(y(:,1))) ;
e = M-m ;
plot(1:N,yi,'-g',1:N,y(:,1),':b') ;
axis([0 N+1 m-0.1*e M+0.1*e]) ;
title('Transient analysis of an ARX[1,1] model') ;
xlabel('Normalized time') ;
ylabel('Model output') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('ideal step response','a realization',0) ;
subplot(212) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
m = min(ym-ystd) ;
M = max(ym+ystd) ;
e = M-m ;
plot(1:N,ym,'-r',1:N,yi,'--g', ...
1:N,ym+ystd,':b',1:N,ym-ystd,':b') ;
axis([0 N+1 m-0.1*e M+0.1*e]) ;
xlabel('Normalized time') ;
ylabel('Model output') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('average step response', ...
'ideal step response', ...
'standard deviation tube',0) ;
FIG = FIG+1 ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% ISLAB_2D Module that estimates the impulse response of an


% ARX[1,1] model.
%
function [hi,h] = islab_2d(a,b,M,N,nr)
%
% Inputs: a # coefficient of AR part (-0.8, by default)
% b # coefficent of X part (1, by default)
% M # length of impulse response (50, by default)
% N # simulation period (100, by default)
% nr # number of realizations/estimations
% (100, by default)
%
% Outputs: hi # ideal impulse response of model (noise free)
% (M-length column vector)
% h # collection of all nr estimations of impulse
% response (M-by-nr matrix)
%
% Author: Helena Haglund (*)
% Bjorn Wittenmark (*)
% Revised: Dan Stefanoiu (**)
% Last upgrade: (*) January 5, 1997
% (**) February 24, 2004
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Department of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%

global FIG ; % Figure number handler


% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~

lambda = 1 ; % Variance of white noise (lambda).

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 5)
nr = 100 ;
end ;
if (isempty(nr))
nr = 100 ;
end ;
nr = abs(fix(nr(1))) ;
if (~nr)
nr = 100 ;
end ;
if (nargin < 4)
N = 100 ;
end ;
if (isempty(N))
N = 100 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 100 ;
end ;
if (nargin < 3)
M = 50 ;
end ;
if (isempty(M))
M = 50 ;
end ;
M = abs(fix(M(1))) ;
if (~M)
M = 50 ;
end ;
if (nargin < 2)
b = 1 ;
end ;
if (isempty(b))
b = 1 ;
end ;
b = b(1) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (nargin < 1)
a = -0.8 ;
end;
if (isempty(a))
a = -0.8 ;
end;
a = a(1) ;
if (abs(a)>=1)
war_err(['<ISLAB_2A>: Model unstable. ' ...
'Reciprocal model considered instead.']) ;
a = 1/a ;
end ;
%
% Generating the Gaussian white noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambda*randn(N,nr) ;
%
% Generating the Pseudo-Random Binary input
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
u = sign(randn(N,nr)) ;
%
% Generating the ideal impulse response
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hi = 0:(M-2) ;
hi = [0 b*(-a).^hi]' ;
%
% Generating the nr realizations
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
y = filter([0 b],[1 a],u) + filter(1,[1 a],e) ;
%
% Estimating the impulse response i.e.
% evaluating the input-output cross-covariance
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
h = [] ;
for k=1:M
h = [h ; sum(y(k:N,:).*u(1:(N-k+1),:))] ;
end ;
h = h/N ; % Note: the variance of input is unit.

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Evaluating the average of estimations


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hm = mean(h')' ;
%
% Evaluating the standard deviation
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hstd = std(h',1)' ;
%
% Plotting
% ~~~~~~~~
figure(FIG),clf ;
fig_look(FIG,2) ;
subplot(211) ;
m = min(min(hi),min(h(:,1))) ;
k = max(max(hi),max(h(:,1))) ;
e = k-m ;
plot(1:M,hi,'-g',1:M,h(:,1),':b') ;
axis([0 M+1 m-0.1*e k+0.1*e]) ;
title('Correlation analysis of an ARX[1,1] model') ;
xlabel('Normalized time') ;
ylabel('Impulse response') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('ideal impulse response','an estimation',0) ;
subplot(212) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
m = min(hm-hstd) ;
k = max(hm+hstd) ;
e = k-m ;
plot(1:M,hm,'-r',1:M,hi,'--g', ...
1:M,hm+hstd,':b',1:M,hm-hstd,':b') ;
axis([0 M+1 m-0.1*e k+0.1*e]) ;
xlabel('Normalized time') ;
ylabel('Impulse response') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('average of estimated impulse response', ...
'ideal impulse response', ...
'standard deviation tube',0) ;
FIG = FIG+1 ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% ISLAB_2L Module that estimates the frequency response of an


% ARX[1,1] model.
%
function [magi,phii,mag,phi,f] = islab_2l(a,b,M,K,N,nr)
%
% Inputs: a # coefficient of AR part (-0.8, by default)
% b # coefficent of X part (1, by default)
% M # length of Hamming window (30, by default)
% K # number of frequency nodes (50, by default)
% N # simulation period (100, by default)
% nr # number of realizations (100, by default)
%
% Outputs: magi # magnitude of ideal frequency response
% (noise free) (K-length vector)
% phii # phase of ideal frequency response
% (noise free) (K-length vector)
% mag # magnitude of all nr estimations of
% frequency response (K-by-nr matrix)
% phi # phase of all nr estimations of
% frequency response (K-by-nr matrix)
% f # frequency axis (semi-logarithmic)
% between 10^(-2) and pi (K-length vector)
%
% Explanation: The frequency response of an ARX[1,1] model is
% estimated through spectral analysis (equation
% of spectral density transfer). This simulator
% shows the Bode diagram of ideal frequency
% response (noise free) and of the estimated
% frequency response averaged over
% nr realisations.
%
% Author: Helena Haglund (*)
% Bjorn Wittenmark (*)
% Revised: Dan Stefanoiu (**)
% Last upgrade: (*) January 5, 1997
% (**) February 24, 2004
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Department of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% BEGIN
%

global FIG ; % Figure number handler


% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~

lambda = 1 ; % Variance of white noise (lambda).


p = -0.8 ; % Pole of input filter (AR[1]).
Ts = 1 ; % Sampling period.
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 6)
nr = 100 ;
end ;
if (isempty(nr))
nr = 100 ;
end ;
nr = abs(fix(nr(1))) ;
if (~nr)
nr = 100 ;
end ;
if (nargin < 5)
N = 100 ;
end ;
if (isempty(N))
N = 100 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 100 ;
end ;
if (nargin < 4)
K = 50 ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (isempty(K))
K = 50 ;
end ;
K = abs(fix(K(1))) ;
if (~K)
K = 50 ;
end ;
if (nargin < 3)
M = 30 ;
end ;
if (isempty(M))
M = 30 ;
end ;
M = max([abs(fix(M(1))) round(N/10) 30]) ;
if (nargin < 2)
b = 1 ;
end ;
if (isempty(b))
b = 1 ;
end ;
b = b(1) ;
if (nargin < 1)
a = -0.8 ;
end;
if (isempty(a))
a = -0.8 ;
end;
a = a(1) ;
if (abs(a)>=1)
war_err(['<ISLAB_2A>: Model unstable. ' ...
'Reciprocal model considered instead.']) ;
a = 1/a ;
end ;
%
% Generating the ideal frequency response
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
f = logspace(-2,pi,K) ; % The frequency axis.
[magi,phii] = dbode([0 b],[1 a],Ts,f) ;
% phii measured in degrees.

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Generating the Gaussian white noise


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambda*randn(N,nr) ;
%
% Generating the Pseudo-Random Binary input
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
u = sign(randn(N,nr)) ;
%
% Filtering and normalizing the input
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
u = filter(1,[1 p],u) ;
u = u./sqrt(ones(N,1)*sum(u.*u)/N) ;
%
% Generating the nr realizations
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
y = filter([0 b],[1 a],u) + filter(1,[1 a],e) ;
%
% Packing the data in a System Identification structure
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mag = [] ;
phi = [] ;
for p=1:nr
D = iddata(y(:,p),u(:,p),Ts) ;
%
% Estimating the frequency response
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
H = spa(D,M,f) ;
%
% Extracting the magnitude and the phase of estimations
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
H = H.ResponseData ;
a = abs(H(1,1,:)) ;
a = reshape(a,K,1) ;
mag = [mag a] ;
a = angle(H(1,1,:)) ;
a = 180*reshape(a,K,1)/pi ;
phi = [phi a] ; % phi measured in degrees.
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Evaluating the average of estimations


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
magm = mean(mag')' ;
phim = mean(phi')' ;
%
% Evaluating the standard deviation
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
magstd = std(mag',1)' ;
phistd = std(phi',1)' ;
%
% Plotting
% ~~~~~~~~
figure(FIG),clf ;
fig_look(FIG,2) ;
subplot(211) ;
loglog(f,magi,'--g',f,mag(:,1),'-.b',f,magm,'-r', ...
f,magm-magstd,':m',f,magm+magstd,':m') ;
a = axis ;
axis([a(1:3) a(4)+0.1*(a(4)-a(3))]) ;
title(['Spectral analysis with Hamming window ' ...
'of length M = ' int2str(M) '.']) ;
xlabel('Normalized frequency [rad/s] (log)') ;
ylabel('Magnitude (log)') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('ideal magnitude','an estimation','average', ...
'standard deviation tube',3) ;
subplot(212) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
semilogx(f,phii,'--g',f,phi(:,1),'-.b',f,phim,'-r', ...
f,phim-phistd,':m',f,phim+phistd,':m') ;
xlabel('Normalized frequency [rad/s] (log)') ;
ylabel('Phase [deg]') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('ideal phase','an estimation','average', ...
'standard deviation tube',3) ;
FIG = FIG+1 ;
%
% END
%

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

%
%CCRRKKVVQQNNWWNN
% ISLAB_3D Module that estimates the parameters of an
% ARX[2,2] model, with the help of
% Least Squares (LS) Method.
%
function [a,b,lambda,magi,phii,mag,phi,f] = ...
islab_3d(at,bt,K,N,nr)
%
% Inputs: at # true coefficients of AR part
% ([-0.4 -0.32], by default)
% bt # true coefficents of X part
% ([0.5 0.03], by default)
% K # number of frequency nodes (50, by default)
% N # simulation period (100, by default)
% nr # number of realizations (100, by default)
%
% Outputs: a # LS estimates of AR coefficients
% (nr-by-2 matrix)
% b # LS estimates of X coefficents
% (nr-by-2 matrix)
% lambda # LS estimates of noise standard deviation
% (nr-length vector)
% magi # magnitude of ideal frequency response
% (noise free) (K-length vector)
% phii # phase of ideal frequency response
% (noise free) (K-length vector)
% mag # magnitude of all nr estimations of
% frequency response (K-by-nr matrix)
% phi # phase of all nr estimations of
% frequency response (K-by-nr matrix)
% f # frequency axis (semi-logarithmic)
% between 10^(-2) and pi (K-length vector)
%
% Explanation: The parameters of an ARX[2,2] model are
% estimated by means of LS Method. This simulator
% shows the estimation errors produced on
% Bode diagram of model, as well as the estimation
% of noise variance.

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Author: Dan Stefanoiu (*)


% Revised: Dan Stefanoiu (*)
% Last upgrade: February 27, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%

global FIG ; % Figure number handler


% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~

lambdat = 1 ; % True variance of white noise.


p = -0.8 ; % Pole of input filter (AR[1]).
Ts = 1 ; % Sampling period.
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 5)
nr = 100 ;
end ;
if (isempty(nr))
nr = 100 ;
end ;
nr = abs(fix(nr(1))) ;
if (~nr)
nr = 100 ;
end ;
if (nargin < 4)
N = 100 ;
end ;
if (isempty(N))
N = 100 ;
end ;
N = abs(fix(N(1))) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (~N)
N = 100 ;
end ;
if (nargin < 3)
K = 50 ;
end ;
if (isempty(K))
K = 50 ;
end ;
K = abs(fix(K(1))) ;
if (~K)
K = 50 ;
end ;
if (nargin < 2)
bt = [0.5 0.03] ;
end ;
if (isempty(bt))
bt = [0.5 0.03] ;
end ;
bt = [0 bt(1:2)] ;
if (nargin < 1)
at = [-0.4 -0.32] ;
end;
if (isempty(at))
at = [-0.4 -0.32] ; ;
end;
at = [1 at(1:2)] ;
a = roots(at) ;
if (abs(a(1))>=1)
war_err(['<ISLAB_3D>: Model unstable. ' ...
'Reciprocal model considered instead.']) ;
a(1) = 1/a(1) ;
end ;
if (abs(a(2))>=1)
war_err(['<ISLAB_3D>: Model unstable. ' ...
'Reciprocal model considered instead.']) ;
a(2) = 1/a(2) ;
end ;
at = poly(a) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Generating the ideal frequency response


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
f = logspace(-2,pi,K) ; % The frequency axis.
[magi,phii] = dbode(bt,at,Ts,f) ;
% phii measured in degrees.
%
% Generating the Gaussian white noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambdat*randn(N,nr) ;
%
% Generating the PRB input
% ~~~~~~~~~~~~~~~~~~~~~~~~
u = sign(randn(N,nr)) ;
%
% Filtering and normalizing the input
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
u = filter(1,[1 p],u) ;
u = u./sqrt(ones(N,1)*sum(u.*u)/N) ;
%
% Generating the nr realizations
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
y = filter(bt,at,u) + filter(1,at,e) ;
%
% Estimating the ARX parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a = [] ;
b = [] ;
lambda = [] ;
mag = [] ;
phi = [] ;
for p=1:nr
[ru,K] = xcov(u(:,p),'biased'); % Constructing the
ru = ru(K>=0) ; % auto-covariance of input.
ru = ru(1:2) ;
[ry,K] = xcov(y(:,p),'biased'); % Constructing the
ry = ry(K>=0) ; % auto-covariance of output.
ry = ry(1:3) ;
% Constructing the
% I/O cross-covariance.

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

[ryu,K] = xcov(y(:,p),u(:,p),'biased') ;
ryu = ryu(K>=-1) ;
ryu = ryu(1:4) ;
R = -[ryu(2) ryu(3) ; ...
ryu(1) ryu(2)] ;
R = [toeplitz(ry(1:2)) R ; ...
R' toeplitz(ru)] ; % Main matrix.
r = [-ry(2) ; -ry(3) ; ryu(3) ; ryu(4)] ; % Free vector.
r = R\r ; % Coefficients.
a = [a ; r(1:2)'] ;
b = [b ; r(3:4)'] ;
e = [y(:,p) ... % Noise estimation.
[0 ; y(1:(N-1),p)] ...
[0 ; 0 ; y(1:(N-2),p)] ...
-[0 ; u(1:(N-1),p)] ...
-[0 ; 0 ; u(1:(N-2),p)]] * [1 ; r] ;
lambda = [lambda ; norm(e)/sqrt(N-4)]; % Standard deviation.
%
% Estimating the frequency response
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[R,r] = dbode([0 b(end,:)],[1 a(end,:)],Ts,f) ;
mag = [mag R] ;
phi = [phi r] ;
end ;
%
% Evaluating the average of parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
am = mean(a) ;
bm = mean(b) ;
%
% Evaluating the average of estimation errors
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
magstd = (magi*ones(1,nr)-mag)' ;
phistd = (phii*ones(1,nr)-phi)' ;
magm = mean(magstd)' ;
phim = mean(phistd)' ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Evaluating the standard deviation


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
magstd = std(magstd,1)' ;
phistd = std(phistd,1)' ;
%
% Plotting
% ~~~~~~~~
figure(FIG),clf ;
fig_look(FIG,2) ;
subplot(211) ;
semilogx(f,magm,'-b', ...
f,magm-magstd,':r',f,magm+magstd,':r') ;
a = axis ;
axis([a(1:3) a(4)+0.1*(a(4)-a(3))]) ;
title(['Estimating an ARX[2,2] model ' ...
'by the Least Squares Method.']) ;
xlabel('Normalized frequency [rad/s] (log)') ;
ylabel('FR magnitude') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('estimation error', ...
'standard deviation tube',0) ;
subplot(212) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
semilogx(f,phim,'-b', ...
f,phim-phistd,':r',f,phim+phistd,':r') ;
xlabel('Normalized frequency [rad/s] (log)') ;
ylabel('FR phase [deg]') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('estimation error', ...
'standard deviation tube',0) ;
FIG = FIG+1 ;
figure(FIG) ;
fig_look(FIG,2) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
plot(1:nr,lambda.^2,'-m',1:nr,ones(nr,1),'-b') ;
a = axis ;
e = a(4)-a(3) ;
axis([0 nr+1 a(3)-0.1*3 a(4)+0.25*e]) ;
title(['Estimating an ARX[2,2] model ' ...

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

'by the Least Squares Method.']) ;


xlabel('Realization index') ;
ylabel('Noise variance') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('estimated','true',3) ;
text(nr/10,a(4)+0.15*e,...
[' True parameters: ' ...
sprintf('%9.4f',[at(2:3) bt(2:3)])]) ;
text(nr/10,a(4)+0.05*e,...
['Estimated parameters: ' ...
sprintf('%9.4f',[am bm])]) ;
FIG = FIG+1 ;
%
% END
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

%
%CCRRKKVVQQNNWWNN
%
% ISLAB_4A Module that estimates an ARX model by using LSM.
%
function [Mid,Did,Dva] = islab_4a(A,B,C,nk,N,sigma,lambda)
%
% Inputs: A # true coefficients of AR part
% ([1 -1.5 0.7], by default)
% B # true coefficients of X part
% ([1 0.5], by default)
% C # true coefficients of MA part (noise filter)
% ([1 -1 0.2], by default)
% nk # intrinsic delay of process (1, by default)
% N # simulation period (250, by default)
% sigma # standard deviation of PRB input
% (1, by default); if null, ARMA or AR
% processes are considered
% lambda # standard deviation of white noise
% (1, by default)
%
% Outputs: Mid # IDMODEL object representing the
% estimated model
% Did # IDDATA object representing the
% data generated for identification
% Dva # IDDATA object representing the
% data generated for validation
%
% Explanation: Data generated by an ARMAX process are employed
% to identify an ARX model with the help of
% Least Squares Method. The estimation is
% consistent, but not the most efficient
% (i.e. the convergence speed is not the best).
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: March 16, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% BEGIN
%

global FIG ; % Figure number handler


% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~

alpha = 3 ; % Weighting factor of


% confidence disks radius.
pf = 1 ; % Plot flag: 0=no, 1=yes.
Na = 8 ; % Maximum index of AR part.
Nb = 8 ; % Maximum index of X part.
Ts = 1 ; % Sampling period.
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 7)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (~lambda)
lambda = 1 ;
end ;
if (nargin < 6)
sigma = 1 ;
end ;
if (isempty(sigma))
sigma = 1 ;
end ;
sigma = abs(sigma(1)) ;
if (nargin < 5)
N = 250 ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (isempty(N))
N = 250 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 250 ;
end ;
if (nargin < 4)
nk = 1 ;
end ;
if (isempty(nk))
nk = 1 ;
end ;
nk = abs(fix(nk(1))) ;
if (~nk)
nk = 1 ;
end ;
if (nargin < 3)
C = [1 -1 0.2] ;
end ;
if (isempty(C))
C = [1 -1 0.2] ;
end ;
if (nargin < 2)
B = [1 0.5] ;
end ;
if (isempty(B))
B = [1 0.5] ;
end ;
if (nargin < 1)
A = [1 -1.5 0.7] ;
end;
if (isempty(A))
A = [1 -1.5 0.7] ; ;
end;
A = roots(A) ;
A(abs(A)>=1) = 1./A(abs(A)>=1) ; % Correct the stability.
A = poly(A) ;
%

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Generating the identification data


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Did = gendata(A,B,C,nk,N,sigma,lambda) ;
%
% Generating the validation data
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dva = gendata(A,B,C,nk,N,sigma,lambda) ;
%
% Estimating all models via LSM
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Na = Na+1 ;
Nb = Nb+1 ;
M = cell(Na,Nb) ; % Cell array of all models.
Lambda = 1000*lambda*ones(Na,Nb) ; % Matrix of noise variances.
Yid = cell(Na,Nb) ; % Cell array of simulated
% outputs when using
% the identification data.
Yva = cell(Na,Nb) ; % Cell array of simulated
% outputs when using
% the validation data.
PEid = cell(Na,Nb) ; % Cell array of prediction
% errors on ident. data.
PEva = cell(Na,Nb) ; % Cell array of prediction
% errors on validation data.
Eid = zeros(Na,Nb) ; % Matrix of fitness values
% evaluated on ident. data.
Eva = zeros(Na,Nb) ; % Matrix of fitness values
% evaluated on validation
% data.
yNid = Did.y-mean(Did.y) ; % Centered y (ident.).
yNva = Dva.y-mean(Dva.y) ; % Centered y (validation).
Viid = zeros(Na,Nb) ; % Validation index matrix
% (identification data).
Viva = zeros(Na,Nb) ; % Validation index matrix
% (validation data).
if (~pf) % Show model performances
war_err([' * Models estimation started. ' ...
'This may take few moments. Please wait...']) ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

for na=1:Na
for nb=1:Nb
if ((na>1) | (nb>1))
Mid = arx(Did,[na-1 nb-1 nk]) ;% Model estimation.
M{na,nb} = Mid ; % Save model & variance.
Lambda(na,nb) = Mid.NoiseVariance ;
PEid{na,nb} = resid(Mid,Did) ; % Save prediction err.
PEva{na,nb} = resid(Mid,Dva) ;
ys = sim(Mid,Did) ; % Save simulated y
Yid{na,nb} = ys.y ; % (noise free).
ys = sim(Mid,Dva) ;
Yva{na,nb} = ys.y ;
% Save fitness values.
Eid(na,nb) = 100*(1-norm(PEid{na,nb}.y)/norm(yNid)) ;
Eva(na,nb) = 100*(1-norm(PEva{na,nb}.y)/norm(yNva)) ;
% Save validation idx.
Viid(na,nb) = valid_LS(Mid,Did) ;
Viva(na,nb) = valid_LS(Mid,Dva) ;
if(pf)
figure(FIG),clf ;
fig_look(FIG,1.5) ;
subplot(321)
plot(1:N,Did.y,'-b',1:N,Yid{na,nb},'-r') ;
title('Identification data') ;
ylabel('Outputs') ;
ys = [min(min(Did.y),min(Yid{na,nb})) ...
max(max(Did.y),max(Yid{na,nb}))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(1.22*N,ys(2)+0.45*dy, ...
['na = ' int2str(na-1) ...
' | nb = ' int2str(nb-1)]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' ...
sprintf('%g',Eid(na,nb)) ' %']) ;
subplot(322)
plot(1:N,Dva.y,'-b',1:N,Yva{na,nb},'-r') ;
title('Validation data') ;
ylabel('Outputs') ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

ys = [min(min(Dva.y),min(Yva{na,nb})) ...
max(max(Dva.y),max(Yva{na,nb}))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' ...
sprintf('%g',Eva(na,nb)) ' %']) ;
set(FIG, ...
'DefaultTextHorizontalAlignment','left');
legend('y','ym',0) ;
set(FIG, ...
'DefaultTextHorizontalAlignment', ...
'center') ;
subplot(323)
plot(1:N,PEid{na,nb}.y,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEid{na,nb}.y) ...
max(PEid{na,nb}.y)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' ...
sprintf('%g',std(PEid{na,nb}.y,1)^2)]);
subplot(324)
plot(1:N,PEva{na,nb}.y,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEva{na,nb}.y) ...
max(PEva{na,nb}.y)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' ...
sprintf('%g',std(PEva{na,nb}.y,1)^2)]);
subplot(325)
set(FIG,'DefaultLineLineWidth',0.5) ;
set(FIG,'DefaultLineMarkerSize',2) ;
[r,K] = xcov(PEid{na,nb}.y,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

r = r(1:K) ;
stem(1:K,r,'-g','filled') ;
xlabel('Normalized time') ;
ylabel('Auto-covariance') ;
ys = [min(r) max(r)] ;
dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' ...
num2str(Viid(na,nb))]) ;
subplot(326)
[r,K] = xcov(PEva{na,nb}.y,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;
r = r(1:K) ;
stem(1:K,r,'-g','filled') ;
xlabel('Normalized time') ;
ylabel('Auto-covariance') ;
ys = [min(r) max(r)] ;
dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' ...
num2str(Viva(na,nb))]) ;
set(FIG, ...
'DefaultTextHorizontalAlignment', ...
'right') ;
text(1.3*K,ys(1)-0.4*dy,'<Press a key>') ;
FIG = FIG+1 ;
pause ;
figure(FIG),clf ;
fig_look(FIG,2) ;
pzmap(Mid,'SD',alpha) ;
title('Poles-Zeros representation') ;
xlabel('Real axis') ;
ylabel('Imaginary axis') ;
ys = axis ;
r = 's' ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (na==2)
r = [] ;
end ;
text(0.8*ys(1),0.9*ys(4), ...
[int2str(na-1) ' pole' r]) ;
r = 's' ;
if (nb==2)
r = [] ;
end ;
text(0.8*ys(2),0.9*ys(4), ...
[int2str(nb-1) ' zero' r]) ;
set(FIG, ...
'DefaultTextHorizontalAlignment','left') ;
text(1.1*ys(2),ys(3),'<Press a key>') ;
FIG = FIG-1 ;
pause ;
end ; % [if (pf)]
end ; % [if ((na>1) | (nb>1))]
end ; % [for nb=1:Nb]
end ; % [for na=1:Na]
if (~pf)
war_err(' ... Done.') ;
end ;
%
% Drawing useful surfaces for selecting the optimal structure
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Na = Na-1 ;
Nb = Nb-1 ;
figure(FIG),clf ; % Noise variance.
fig_look(FIG,2) ;
[na,nb] = F_test2(Lambda,N) ;
Lambda(Lambda<eps) = eps ;
Mid = 10*log10(Lambda) ;
surf(0:Nb,0:Na,Mid) ;
ys = [min(min(Mid)) max(max(Mid))] ;
dy = ys(2) - ys(1) ;
axis([0 Nb 0 Na ys(1) ys(2)+0.2*dy]) ;
view([125,30]) ;
title(['Estimated noise variance surface. ' ...

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

'F-test optimum: na = ' int2str(na-1) ...


', nb = ' int2str(nb-1) '.']) ;
xlabel('nb') ;
ylabel('na') ;
zlabel('\lambda^2 [dB]') ;
text(nb-1,na-1,Mid(na,nb)+0.02*dy,'o') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
text(Nb,1.5*Na,ys(1),'<Press a key>') ;
FIG = FIG+1 ;
pause
figure(FIG),clf ; % Fitness: identification.
fig_look(FIG,2) ;
ys = [min(min(Eid)) max(max(Eid))] ;
[na,nb] = F_test2(ys(2)-Eid,N) ;
surf(0:Nb,0:Na,Eid) ;
dy = ys(2) - ys(1) ;
axis([0 Nb 0 Na ys(1) ys(2)+0.2*dy]) ;
view([125,30]) ;
title(['Fitness values: identification data. ' ...
'F-test optimum: na = ' int2str(na-1) ...
', nb = ' int2str(nb-1) '.']) ;
xlabel('nb') ;
ylabel('na') ;
zlabel('E_N [%]') ;
text(nb-1,na-1,Eid(na,nb)+0.02*dy,'o') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
text(Nb,1.5*Na,ys(1),'<Press a key>') ;
FIG = FIG+1 ;
pause
figure(FIG),clf ; % Fitness: validation.
fig_look(FIG,2) ;
ys = [min(min(Eva)) max(max(Eva))] ;
[na,nb] = F_test2(ys(2)-Eva,N) ;
surf(0:Nb,0:Na,Eva) ;
dy = ys(2) - ys(1) ;
axis([0 Nb 0 Na ys(1) ys(2)+0.2*dy]) ;
view([125,30]) ;
title(['Fitness values: validation data. ' ...
'F-test optimum: na = ' int2str(na-1) ...
', nb = ' int2str(nb-1) '.']) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

xlabel('nb') ;
ylabel('na') ;
zlabel('E_N [%]') ;
text(nb-1,na-1,Eva(na,nb)+0.02*dy,'o') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
text(Nb,1.5*Na,ys(1),'<Press a key>') ;
FIG = FIG+1 ;
pause
figure(FIG),clf ; % GAIC-Rissanen.
fig_look(FIG,2) ;
[na,nb,Mid] = GAIC_R2(Lambda,N) ;
surf(0:Nb,0:Na,Mid) ;
ys = [min(min(Mid)) max(max(Mid))] ;
dy = ys(2) - ys(1) ;
axis([0 Nb 0 Na ys(1) ys(2)+0.2*dy]) ;
view([125,30]) ;
title(['Akaike-Rissanen criterion. ' ...
'Optimum: na = ' int2str(na-1) ...
', nb = ' int2str(nb-1) '.']) ;
xlabel('nb') ;
ylabel('na') ;
zlabel('GAIC-R') ;
text(nb-1,na-1,Mid(na,nb)+0.02*dy,'o') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
text(Nb,1.5*Na,ys(1),'<Press a key>') ;
FIG = FIG+1 ;
pause
%
% Selecting the optimal structure
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
na = input(' # Insert optimal indices [na nb]: ') ;
na = abs(round(na(1:2))) ;
nb = min(Nb,na(2))+1 ;
na = min(Na,na(1))+1 ;
Mid = M{na,nb} ;
Yid = Yid{na,nb} ;
Yva = Yva{na,nb} ;
PEid = PEid{na,nb}.y ;
PEva = PEva{na,nb}.y ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

Eid = Eid(na,nb) ;
Eva = Eva(na,nb) ;
Viid = Viid(na,nb) ;
Viva = Viva(na,nb) ;
war_err(' o Optimum model: ') ;
Mid
war_err([blanks(25) '<Press a key>']) ;
pause
%
% Plotting model performances
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~
figure(FIG),clf ;
fig_look(FIG,1.5) ;
subplot(321)
plot(1:N,Did.y,'-b',1:N,Yid,'-r') ;
title('Identification data') ;
ylabel('Outputs') ;
ys = [min(min(Did.y),min(Yid)) ...
max(max(Did.y),max(Yid))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(1.22*N,ys(2)+0.45*dy, ...
['na = ' int2str(na-1) ...
' | nb = ' int2str(nb-1)]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' sprintf('%g',Eid) ' %']) ;
subplot(322)
plot(1:N,Dva.y,'-b',1:N,Yva,'-r') ;
title('Validation data') ;
ylabel('Outputs') ;
ys = [min(min(Dva.y),min(Yva)) ...
max(max(Dva.y),max(Yva))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' sprintf('%g',Eva) ' %']) ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('y','ym',0) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

subplot(323)
plot(1:N,PEid,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEid) max(PEid)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' sprintf('%g',std(PEid,1)^2)]) ;
subplot(324)
plot(1:N,PEva,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEva) max(PEva)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' sprintf('%g',std(PEva,1)^2)]) ;
subplot(325)
set(FIG,'DefaultLineLineWidth',0.5) ;
set(FIG,'DefaultLineMarkerSize',2) ;
[r,K] = xcov(PEid,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;
r = r(1:K) ;
stem(1:K,r,'-g','filled') ;
xlabel('Normalized time') ;
ylabel('Auto-covariance') ;
ys = [min(r) max(r)] ;
dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' num2str(Viid)]) ;
subplot(326)
[r,K] = xcov(PEva,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;
r = r(1:K) ;
stem(1:K,r,'-g','filled') ;
xlabel('Normalized time') ;
ylabel('Auto-covariance') ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

ys = [min(r) max(r)] ;
dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' num2str(Viva)]) ;
set(FIG,'DefaultTextHorizontalAlignment','right') ;
text(1.3*K,ys(1)-0.4*dy,'<Press a key>') ;
FIG = FIG+1 ;
pause ;
figure(FIG),clf ;
fig_look(FIG,2) ;
pzmap(Mid,'SD',alpha) ;
title('Poles-Zeros representation') ;
xlabel('Real axis') ;
ylabel('Imaginary axis') ;
ys = axis ;
r = 's' ;
if (na==2)
r = [] ;
end ;
text(0.8*ys(1),0.9*ys(4), ...
[int2str(na-1) ' pole' r]) ;
r = 's' ;
if (nb==2)
r = [] ;
end ;
text(0.8*ys(2),0.9*ys(4), ...
[int2str(nb-1) ' zero' r]) ;
%
% END
%
% F_TEST2 Module that evaluates the optimum structural
% orders through the F-test, when identifying
% a model with 2 structural indexes (ARX, ARMA).
%
function [na,nb] = F_test2(Lambda,N)
%
% Inputs: Lambda # estimated noise variance matrix
% N # size of measured data set

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Outputs: na # optimum row order


% nb # optimum column order
%
% Explanation: The matrix of estimated noise variances
% includes Na rows and Nb columns. The F-test
% is evaluated for each element (i,j) of matrix
% by considering adjacent elements (i+1,j) and
% (i,j+1). From the resulted values, only the
% ones inferior to 4/N are selected. To meet the
% Parsimony Principle, the biggest of these values
% is considered when returning the optimum
% structural orders na and nb. Note that the
% structural indices result by decrementing
% na and nb with 1.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: March 8, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<F_TEST2>: ' ;
E1 = [FN 'Missing, empty or null N. Empty outputs. Exit.'] ;
E2 = [FN 'Missing or empty Lambda. Empty outputs. Exit.'] ;
E3 = [FN 'No valid model detected. Empty outputs. Exit.'] ;
W1 = [FN 'Inconsistent Lambda. Coarse structure returned.'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
na = [] ;
nb = [] ;
if (nargin < 2)
war_err(E1) ;
return ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (isempty(N))
war_err(E1) ;
return ;
end ;
N = abs(fix(N(1))) ;
if (~N)
war_err(E1) ;
return ;
end ;
N = 4/N ;
if (nargin < 1)
war_err(E2) ;
return ;
end ;
if (isempty(Lambda))
war_err(E2) ;
return ;
end ;
Lambda = abs(Lambda) ;
Lambda(~Lambda) = eps ;
%
% Evaluating the F-test
% ~~~~~~~~~~~~~~~~~~~~~
[na,nb] = size(Lambda) ;
if ((na<2) & (nb<2))
war_err(W1) ;
elseif ((na<2) | (nb<2))
if (na<2)
Lambda = (Lambda(1:(nb-1))-Lambda(2:nb))./Lambda(2:nb) ;
else
Lambda = (Lambda(1:(na-1))-Lambda(2:na))./Lambda(2:na) ;
end ;
Lambda = Lambda - N ;
Lambda(Lambda>=0) = -Inf ;
if (na<2)
[Lambda,nb] = max(Lambda) ;
else
[Lambda,na] = max(Lambda) ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (isinf(Lambda))
na = [] ;
nb = [] ;
war_err(E3) ;
end ;
else
Na = na ;
Nb = nb ;
Fr = (Lambda(1:(na-1),:)-Lambda(2:na,:))./Lambda(2:na,:)-N ;
Fc = (Lambda(:,1:(nb-1))-Lambda(:,2:nb))./Lambda(:,2:nb)-N ;
Fr(Fr>=0) = -Inf ;
Fc(Fc>=0) = -Inf ;
[Fr,i] = max(Fr) ;
if (Na<3)
j = i ;
i = 1 ;
else
[Fr,j] = max(Fr) ;
i = i(j) ;
end ;
[Fc,na] = max(Fc) ;
if (Nb<3)
nb = 1 ;
else
[Fc,nb] = max(Fc) ;
na = na(nb) ;
end ;
if (isinf(Fr) & isinf(Fc))
na = [] ;
nb = [] ;
war_err(E3) ;
elseif (Fr>Fc)
na = i ;
nb = j ;
end ;
end ;
%
% END
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% GAIC_R2 Module that evaluates the optimum structural


% orders through Akaike criterion, generalized
% by Rissanen (GAIC_R), when identifying a
% model with 2 structural indexes (ARX, ARMA).
%
function [na,nb,GAICR] = GAIC_R2(Lambda,N)
%
%
% Inputs: Lambda # estimated noise variance matrix
% N # size of measured data set
%
% Outputs: na # optimum row order
% nb # optimum column order
% GAICR # values of GAIC_R criterion
%
% Explanation: The matrix of estimated noise variances
% includes Na rows and Nb columns. The GAIC_R
% criterion is evaluated for each element (i,j)
% of matrix. To select the optimum structural
% orders na and nb, the smallest of these values
% is considered. Note that the structural indices
% result by decrementing na and nb with 1.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: March 8, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<GAIC_R2>: ' ;
E1 = [FN 'Missing, empty or null N. Empty outputs. Exit.'] ;
E2 = [FN 'Missing or empty Lambda. Empty outputs. Exit.'] ;
E3 = [FN 'No valid model detected. Empty outputs. Exit.'] ;
W1 = [FN 'Inconsistent Lambda. Coarse structure returned.'] ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Faults preventing
% ~~~~~~~~~~~~~~~~~
na = [] ;
nb = [] ;
GAICR = [] ;
if (nargin < 2)
war_err(E1) ;
return ;
end ;
if (isempty(N))
war_err(E1) ;
return ;
end ;
N = abs(fix(N(1))) ;
if (~N)
war_err(E1) ;
return ;
end ;
N = sqrt(N)/N ;
if (nargin < 1)
war_err(E2) ;
return ;
end ;
if (isempty(Lambda))
war_err(E2) ;
return ;
end ;
Lambda = abs(Lambda) ;
Lambda(~Lambda) = eps ;
%
% Evaluating the GAIC_R criterion
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[na,nb] = size(Lambda) ;
GAICR = log(Lambda) + ...
N*((1:na)'*ones(1,nb) + ones(na,1)*(1:nb)-2) ;
if ((na<2) & (nb<2))
war_err(W1) ;
elseif (na<2)
[Lambda,nb] = min(GAICR) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

elseif (nb<2)
[Lambda,na] = min(GAICR) ;
else
[Lambda,na] = min(GAICR) ;
[Lambda,nb] = min(Lambda) ;
na = na(nb) ;
end ;
%
% END
%
% GENDATA Module that generates data from an ARX model with
% colored noise (or ARMAX model).
%
function [D,V,P] = gendata(A,B,C,nk,N,sigma,lambda)
%
% Inputs: A # true coefficients of AR part
% ([1 -1.5 0.7], by default)
% B # true coefficients of X part
% ([1 0.5], by default)
% C # true coefficients of MA part (noise filter)
% ([1 -1 0.2], by default)
% nk # intrinsic delay of process (1, by default)
% N # simulation period (250, by default)
% sigma # standard deviation of PRB input
% (1, by default); if null, ARMA or AR
% processes are considered
% lambda # standard deviation of white noise
% (1, by default)
% if null, noise free ARX or AR processes
% are considered
%
% Outputs: D # IDDATA model representing the
% I/O generated data
% V # IDDATA model representing the
% I/O noise generated data
% (white noise as input, colored noise
% as output)
% P # IDMODEL object representing the
% process that provided the data

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Explanation: An ARMAX model is stimulated with a PRB input


% with 2 values (+1 and -1). The generated input
% and the observed output are returned. Note that
% various processes can be used, by setting sigma
% and/or lambda to null.
%
% Author: Helena Haglund (*)
% Bjorn Wittenmark (*)
% Revised: Dan Stefanoiu (**)
%
% Last upgrade: (*) January 5, 1997
% (**) March 10, 2004
%
% Copyright: (*) Lund Institute of Technology, SWEDEN
% Dept. of Automatic Control
% (**) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 7)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (nargin < 6)
sigma = 1 ;
end ;
if (isempty(sigma))
sigma = 1 ;
end ;
sigma = abs(sigma(1)) ;
if (nargin < 5)
N = 250 ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (isempty(N))
N = 250 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 250 ;
end ;
if (nargin < 4)
nk = 1 ;
end ;
if (isempty(nk))
nk = 1 ;
end ;
nk = abs(fix(nk(1))) ;
if (~nk)
nk = 1 ;
end ;
if (nargin < 3)
C = [1 -1 0.2] ;
end ;
if (isempty(C))
C = [1 -1 0.2] ;
end ;
if (nargin < 2)
B = [1 0.5] ;
end ;
if (isempty(B))
B = [1 0.5] ;
end ;
if (nargin < 1)
A = [1 -1.5 0.7] ;
end;
if (isempty(A))
A = [1 -1.5 0.7] ; ;
end;
A = roots(A) ;
A(abs(A)>=1) = 1./A(abs(A)>=1) ; % Correct the stability.
A = poly(A) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Generating the Gaussian white noise


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambda*randn(N,1) ;
%
% Generating the Gaussian colored noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
V = filter(C,1,e) ;
V = iddata(V,e) ; % White noise: V.u
% Colored noise: V.y
%
% Generating the PRB input
% ~~~~~~~~~~~~~~~~~~~~~~~~
u = sigma*sign(randn(N,1)) ;
%
% Constructing the data provider model
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P = idpoly(A,[zeros(1,nk) B],C,1,1,lambda*lambda) ;
%
% Generating the data
% ~~~~~~~~~~~~~~~~~~~
D = iddata(sim(P,[u e]),u) ;
%
% END
%
% VALID_LS Module that evaluates the validation index of
% a model, by using the specified Data
% (appropriate for Least Squares Method).
%
function vi = valid_LS(Model,Data)
%
% Inputs: Model # IDMODEL object representing the model
% to validate
% Data # IDDATA object representing the validation
% data set
% Outputs: vi # validation index:
% 0 = invalid model
% 1 = weak validity
% 2 = regular validity
% 3 = extended validity

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Explanation: The whitening test for LS Method is employed


% to provide the validity index. See theory for
% more details.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
%
% Last upgrade: March 13, 2004
%
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<VALID_LS>: ' ;
E1 = [FN 'Missing or empty Model. Empty output. Exit.'] ;
E2 = [FN 'Missing or empty Data. Empty output. Exit.'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
vi = [] ;
if (nargin < 2)
war_err(E2) ;
return ;
end ;
if (isempty(Data))
war_err(E2) ;
return ;
end ;
if (nargin < 1)
war_err(E1) ;
return ;
end ;
if (isempty(Model))
war_err(E1) ;
return ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Evaluating the prediction errors


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = pe(Model,Data) ;
%
% Evaluating the auto-correlation sequence
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[e,k] = xcorr(e.y,'coeff') ;
e = e(k>=0) ;
k = length(e) ;
e = e*sqrt(k) ;
%
% Testing the validity
% ~~~~~~~~~~~~~~~~~~~~
vi = [(abs(e)<=2.17) ...
(abs(e)<=1.96) ...
(abs(e)<=1.808)] ;
vi = sum(vi)/k ;
vi = sum(vi >= [0.97 0.95 0.93]) ;
%
% END
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

%
%CCRRKKVVQQNNWWNN
%
% ISLAB_5A Module that estimates an ARMAX model by using MPEM.
%
function [Mid,Did,Dva] = islab_5a(A,B,C,nk,N,sigma,lambda)
%
% Inputs: A # true coefficients of AR part
% ([1 -1.5 0.7], by default)
% B # true coefficients of X part
% ([1 0.5], by default)
% C # true coefficients of MA part (noise filter)
% ([1 -1 0.2], by default)
% nk # intrinsic delay of process (1, by default)
% N # simulation period (250, by default)
% sigma # standard deviation of PRB input
% (1, by default); if null, ARMA or AR
% processes are considered
% lambda # standard deviation of white noise
% (1, by default)
%
% Outputs: Mid # IDMODEL object representing the
% estimated model
% Did # IDDATA object representing the
% data generated for identification
% Dva # IDDATA object representing the
% data generated for validation
%
% Explanation: Data generated by an ARMAX process are employed
% to identify an ARMAX model with the help of
% Minimum Prediction Error Method (MPEM).
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: March 16, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

global FIG ; % Figure number handler


% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~

alpha = 3 ; % Weighting factor of


% confidence disks radius.
pf = 1 ; % Plot flag: 0=no, 1=yes.
Na = 5 ; % Maximum index of AR part.
Nb = 5 ; % Maximum index of X part.
Nc = 5 ; % Maximum index of MA part.
Ts = 1 ; % Sampling period.
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 7)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (~lambda)
lambda = 1 ;
end ;
if (nargin < 6)
sigma = 1 ;
end ;
if (isempty(sigma))
sigma = 1 ;
end ;
sigma = abs(sigma(1)) ;
if (nargin < 5)
N = 250 ;
end ;
if (isempty(N))
N = 250 ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

N = abs(fix(N(1))) ;
if (~N)
N = 250 ;
end ;
if (nargin < 4)
nk = 1 ;
end ;
if (isempty(nk))
nk = 1 ;
end ;
nk = abs(fix(nk(1))) ;
if (~nk)
nk = 1 ;
end ;
if (nargin < 3)
C = [1 -1 0.2] ;
end ;
if (isempty(C))
C = [1 -1 0.2] ;
end ;
if (nargin < 2)
B = [1 0.5] ;
end ;
if (isempty(B))
B = [1 0.5] ;
end ;
if (nargin < 1)
A = [1 -1.5 0.7] ;
end;
if (isempty(A))
A = [1 -1.5 0.7] ; ;
end;
A = roots(A) ;
A(abs(A)>=1) = 1./A(abs(A)>=1) ; % Correct the stability.
A = poly(A) ;
%
% Constructing the data provider process
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P = idpoly(A,[zeros(1,nk) B],C,1,1,Ts) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

%
% Generating the identification data
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Did = gen_data(P,N,sigma,lambda) ;
%
% Generating the validation data
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dva = gen_data(P,N,sigma,lambda) ;
%
% Estimating all models via MPEM
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Na = Na+1 ;
Nb = Nb+1 ;
Nc = Nc+1 ;
M = cell(Na,Nb,Nc) ; % Cell array of all models.
% Matrix of noise variances.
Lambda = 1000*lambda*ones(Na,Nb,Nc) ;
Yid = cell(Na,Nb,Nc) ; % Cell array of simulated
% outputs when using
% the identification data.
Yva = cell(Na,Nb,Nc) ; % Cell array of simulated
% outputs when using
% the validation data.
PEid = cell(Na,Nb,Nc) ; % Cell array of prediction
% errors on ident. data.
PEva = cell(Na,Nb,Nc) ; % Cell array of prediction
% errors on validation data.
Eid = zeros(Na,Nb,Nc) ; % Matrix of fitness values
% evaluated on ident. data.
Eva = zeros(Na,Nb,Nc) ; % Matrix of fitness values
% evaluated on validation
% data.
yNid = Did.y-mean(Did.y) ; % Centered y (ident.).
yNva = Dva.y-mean(Dva.y) ; % Centered y (validation).
Viid = zeros(Na,Nb,Nc) ; % Validation index matrix
% (identification data).
Viva = zeros(Na,Nb,Nc) ; % Validation index matrix
% (validation data).

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

optidx = zeros(3,3) ; % Optimal indexes. Rows:


% - prediction error
% - fitness on ident. data
% - fitness on valid. data
% - GAIC-Rissanen
% - selected by user
if (~pf) % Show model performances
war_err([blanks(4) '* Models estimation started. ' ...
'This may take few moments. ' ...
'Please wait...']) ;
end ;
for na=1:Na
if (~pf)
disp([blanks(10) 'na = ' int2str(na-1)]) ;
end ;
for nb=1:Nb
if (~pf)
disp([blanks(16) 'nb = ' int2str(nb-1)]) ;
end ;
for nc=1:Nc
if (~pf)
disp([blanks(22) 'nc = ' int2str(nc-1)]) ;
end ;
if ((na>1) | (nb>1) | (nc>1))
if ((nb<2) & (nc<2)) % Model estimation.
Mid = ar(Did.y,na-1) ;
Mid.b = 0 ;
Mid.nk = nk ;
elseif (nb<2)
Mid = armax(Did.y,[na-1 nc-1]) ;
Mid.b = 0 ;
Mid.nk = nk ;
else
Mid = armax(Did,[na-1 nb-1 nc-1 nk]) ;
end ;
M{na,nb,nc} = Mid ; % Save model & variance.
Lambda(na,nb,nc) = Mid.NoiseVariance ;
% Save prediction errors.
PEid{na,nb,nc} = resid(Mid,Did) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

PEva{na,nb,nc} = resid(Mid,Dva) ;
ys = compare(Mid,Did) ; % Save simulated outputs
Yid{na,nb,nc} = ys{1,1}.y ;% (noise free, initial
ys = compare(Mid,Dva) ; % conditions set for the
Yva{na,nb,nc} = ys{1,1}.y ;% best fit).
% Save fitness values.
Eid(na,nb,nc) = ...
100*(1-norm(PEid{na,nb,nc}.y)/norm(yNid)) ;
Eva(na,nb,nc) = ...
100*(1-norm(PEva{na,nb,nc}.y)/norm(yNva)) ;
% Save validation indices.
Viid(na,nb,nc) = valid_LS(Mid,Did) ;
Viva(na,nb,nc) = valid_LS(Mid,Dva) ;
% Upgrade optimal indices.
if ((na>1) & (nb>1) & (nc>1))
% F-test on prediction error.
if (~sum(optidx(1,:)))
ys = [Lambda(na-1,nb,nc) ...
Lambda(na,nb-1,nc) ...
Lambda(na,nb,nc-1)] ;
ys = ys/Lambda(na,nb,nc) - 1 ;
if (sum(ys<(4/N))==3) | ...
((na==Na) & (nb==Nb) & (nc==Nc))
optidx(1,:) = [na nb nc] ;
end ;
end ;
if (~sum(optidx(2,:))) % F-test on fitness
% (identification).
ys = [Eid(na-1,nb,nc) ...
Eid(na,nb-1,nc) ...
Eid(na,nb,nc-1)] ;
ys = 1-ys/Eid(na,nb,nc) ;
if (sum(ys<(4/N))==3) | ...
((na==Na) & (nb==Nb) & (nc==Nc))
optidx(2,:) = [na nb nc] ;
end ;
end ;
if (~sum(optidx(3,:))) % F-test on fitness
% (validation).

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

ys = [Eva(na-1,nb,nc) ...
Eva(na,nb-1,nc) ...
Eva(na,nb,nc-1)] ;
ys = 1-ys/Eva(na,nb,nc) ;
if (sum(ys<(4/N))==3) | ...
((na==Na) & (nb==Nb) & (nc==Nc))
optidx(3,:) = [na nb nc] ;
end ;
end ;
end ; % [if ((na>1) & (nb>1) & (nc>1))]
if (pf) % Show model performances.
figure(FIG),clf ;
fig_look(FIG,1.5) ;
subplot(321)
plot(1:N,Did.y,'-b',1:N,Yid{na,nb,nc},'-r') ;
title('Identification data') ;
ylabel('Outputs') ;
ys = [min(min(Did.y),min(Yid{na,nb,nc})) ...
max(max(Did.y),max(Yid{na,nb,nc}))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(1.22*N,ys(2)+0.45*dy, ...
['na = ' int2str(na-1) ...
' | nb = ' int2str(nb-1) ...
' | nc = ' int2str(nc-1)]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' ...
sprintf('%g',Eid(na,nb,nc)) ' %']) ;
subplot(322)
plot(1:N,Dva.y,'-b',1:N,Yva{na,nb,nc},'-r') ;
title('Validation data') ;
ylabel('Outputs') ;
ys = [min(min(Dva.y),min(Yva{na,nb,nc})) ...
max(max(Dva.y),max(Yva{na,nb,nc}))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' ...
sprintf('%g',Eva(na,nb,nc)) ' %']) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

set(FIG, ...
'DefaultTextHorizontalAlignment','left');
legend('y','ym',0) ;
set(FIG, ...
'DefaultTextHorizontalAlignment', ...
'center') ;
subplot(323)
plot(1:N,PEid{na,nb,nc}.y,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEid{na,nb,nc}.y) ...
max(PEid{na,nb,nc}.y)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' ...
sprintf('%g', ...
std(PEid{na,nb,nc}.y,1)^2)]) ;
subplot(324)
plot(1:N,PEva{na,nb,nc}.y,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEva{na,nb,nc}.y) ...
max(PEva{na,nb,nc}.y)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' ...
sprintf('%g', ...
std(PEva{na,nb,nc}.y,1)^2)]) ;
subplot(325)
set(FIG,'DefaultLineLineWidth',0.5) ;
set(FIG,'DefaultLineMarkerSize',2) ;
[r,K] = xcov(PEid{na,nb,nc}.y,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;
r = r(1:K) ;
stem(1:K,r,'-g','filled') ;
xlabel('Normalized time') ;
ylabel('Auto-covariance') ;
ys = [min(r) max(r)] ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' ...
num2str(Viid(na,nb,nc))]) ;
subplot(326)
[r,K] = xcov(PEva{na,nb,nc}.y,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;
r = r(1:K) ;
stem(1:K,r,'-g','filled') ;
xlabel('Normalized time') ;
ylabel('Auto-covariance') ;
ys = [min(r) max(r)] ;
dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' ...
num2str(Viva(na,nb,nc))]) ;
set(FIG, ...
'DefaultTextHorizontalAlignment', ...
'right') ;
text(1.3*K,ys(1)-0.4*dy,'<Press a key>') ;
FIG = FIG+1 ;
pause ;
figure(FIG),clf ;
fig_look(FIG,2) ;
pzmap(Mid,'b','SD',alpha) ;
title('Poles-Zeros representation (system)') ;
xlabel('Real axis') ;
ylabel('Imaginary axis') ;
ys = axis ;
r = 's' ;
if (na==2)
r = [] ;
end ;
text(0.8*ys(1),0.9*ys(4), ...
[int2str(na-1) ' pole' r]) ;
r = 's' ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (nb==2)
r = [] ;
end ;
text(0.8*ys(2),0.9*ys(4), ...
[int2str(nb-1) ' zero' r]) ;
set(FIG, ...
'DefaultTextHorizontalAlignment','left') ;
text(1.1*ys(2),ys(3),'<Press a key>') ;
FIG = FIG+1 ;
pause ;
if ((na>1) | (nc>1))
Mid.b = Mid.c ;
Mid.nk = 0 ;
figure(FIG),clf ;
fig_look(FIG,2) ;
pzmap(Mid,'r','SD',alpha) ;
title('Poles-Zeros representation (noise)') ;
xlabel('Real axis') ;
ylabel('Imaginary axis') ;
ys = axis ;
r = 's' ;
if (na==2)
r = [] ;
end ;
text(0.8*ys(1),0.9*ys(4), ...
[int2str(na-1) ' pole' r]) ;
r = 's' ;
if (nc==2)
r = [] ;
end ;
text(0.8*ys(2),0.9*ys(4), ...
[int2str(nc-1) ' zero' r]) ;
set(FIG, ...
'DefaultTextHorizontalAlignment','left');
text(1.1*ys(2),ys(3),'<Press a key>') ;
pause ;
end ;
FIG = FIG-2 ;
end ; % [if (pf)]

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

end ; % [if ((na>1) | (nb>1)) ]


end ; % [for nc=1:Nc]
end ; % [for nb=1:Nb]
end ; % [for na=1:Na]
if (~pf)
war_err([blanks(6) '... Done.']) ;
end ;
%
% Proposing the optimal structure
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[na,nb,nc] = GAIC_R3(Lambda,N) ;
optidx = [optidx ; [na nb nc]] ;
war_err('* Proposed optimal indices:') ;
disp(['<F-test on prediction error>: ' ...
'[na nb nc] = [' sprintf(' %d',optidx(1,:)-1) ']']) ;
M{optidx(1,1),optidx(1,2),optidx(1,3)}
disp(['<F-test on fitness (identification data)>: ' ...
'[na nb nc] = [' sprintf(' %d',optidx(2,:)-1) ']']) ;
M{optidx(2,1),optidx(2,2),optidx(2,3)}
disp(['<F-test on fitness (validation data)>: ' ...
'[na nb nc] = [' sprintf(' %d',optidx(3,:)-1) ']']) ;
M{optidx(3,1),optidx(3,2),optidx(3,3)}
disp(['<GAIC-Rissanen criterion>: ' ...
'[na nb nc] = [' sprintf(' %d',optidx(4,:)-1) ']']) ;
M{optidx(4,1),optidx(4,2),optidx(4,3)}
%
% Selecting the optimal structure
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
disp(' ') ;
na = input('# Insert optimal indices [na nb nc]: ') ;
na = abs(round(na(1:3))) ;
nc = min(Nc,na(3))+1 ;
nb = min(Nb,na(2))+1 ;
na = min(Na,na(1))+1 ;
optidx = [optidx ; [na nb nc]-1] ;
Mid = M{na,nb,nc} ;
Yid = Yid{na,nb,nc} ;
Yva = Yva{na,nb,nc} ;
PEid = PEid{na,nb,nc}.y ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

PEva = PEva{na,nb,nc}.y ;
Eid = Eid(na,nb,nc) ;
Eva = Eva(na,nb,nc) ;
Viid = Viid(na,nb,nc) ;
Viva = Viva(na,nb,nc) ;
war_err(' o Optimum model: ') ;
Mid
war_err([blanks(25) '<Press a key>']) ;
pause
%
% Plotting model performances
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(321)
plot(1:N,Did.y,'-b',1:N,Yid,'-r') ;
title('Identification data') ;
ylabel('Outputs') ;
ys = [min(min(Did.y),min(Yid)) ...
max(max(Did.y),max(Yid))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(1.22*N,ys(2)+0.45*dy, ...
['na = ' int2str(na-1) ...
' | nb = ' int2str(nb-1) ...
' | nc = ' int2str(nc-1)]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' sprintf('%g',Eid) ' %']) ;
subplot(322)
plot(1:N,Dva.y,'-b',1:N,Yva,'-r') ;
title('Validation data') ;
ylabel('Outputs') ;
ys = [min(min(Dva.y),min(Yva)) ...
max(max(Dva.y),max(Yva))] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.05*dy, ...
['Fitness E_N = ' sprintf('%g',Eva) ' %']) ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

legend('y','ym',0) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
subplot(323)
plot(1:N,PEid,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEid) max(PEid)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' sprintf('%g',std(PEid,1)^2)]) ;
subplot(324)
plot(1:N,PEva,'-m') ;
ylabel('Prediction error') ;
ys = [min(PEva) max(PEva)] ;
dy = ys(2)-ys(1) ;
axis([0 N+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(N/2,ys(2)+0.07*dy, ...
['\lambda^2 = ' sprintf('%g',std(PEva,1)^2)]) ;
subplot(325)
set(FIG,'DefaultLineLineWidth',0.5) ;
set(FIG,'DefaultLineMarkerSize',2) ;
[r,K] = xcov(PEid,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;
r = r(1:K) ;
stem(1:K,r,'-g','filled') ;
xlabel('Normalized time') ;
ylabel('Auto-covariance') ;
ys = [min(r) max(r)] ;
dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' num2str(Viid)]) ;
subplot(326)
[r,K] = xcov(PEva,'unbiased') ;
r = r(K>=0) ;
K = ceil(length(r)/2) ;
r = r(1:K) ;
stem(1:K,r,'-g','filled') ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

xlabel('Normalized time') ;
ylabel('Auto-covariance') ;
ys = [min(r) max(r)] ;
dy = ys(2)-ys(1) ;
axis([0 K+1 ys(1)-0.05*dy ys(2)+0.2*dy]) ;
text(K/2,ys(2)+0.05*dy, ...
['Validation index = ' num2str(Viva)]) ;
set(FIG,'DefaultTextHorizontalAlignment','right') ;
text(1.3*K,ys(1)-0.4*dy,'<Press a key>') ;
FIG = FIG+1 ;
pause ;
figure(FIG),clf
fig_look(FIG,2) ;
pzmap(Mid,'SD',alpha) ;
title('Poles-Zeros representation (system)') ;
xlabel('Real axis') ;
ylabel('Imaginary axis') ;
ys = axis ;
r = 's' ;
if (na==2)
r = [] ;
end ;
text(0.8*ys(1),0.9*ys(4), ...
[int2str(na-1) ' pole' r]) ;
r = 's' ;
if (nb==2)
r = [] ;
end ;
text(0.8*ys(2),0.9*ys(4), ...
[int2str(nb-1) ' zero' r]) ;
FIG = FIG+1 ;
if ((na>1) | (nc>1))
pause ;
P = Mid ;
P.b = P.c ;
P.nk = 0 ;
figure(FIG),clf ;
fig_look(FIG,2) ;
pzmap(P,'r','SD',alpha) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

title('Poles-Zeros representation (noise)') ;


xlabel('Real axis') ;
ylabel('Imaginary axis') ;
ys = axis ;
r = 's' ;
if (na==2)
r = [] ;
end ;
text(0.8*ys(1),0.9*ys(4), ...
[int2str(na-1) ' pole' r]) ;
r = 's' ;
if (nc==2)
r = [] ;
end ;
text(0.8*ys(2),0.9*ys(4), ...
[int2str(nc-1) ' zero' r]) ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
text(1.1*ys(2),ys(3),'<Press a key>') ;
FIG = FIG+1 ;
pause ;
end ;
%
% END
%
% GAIC_R3 Module that evaluates the optimum structural
% orders through Akaike criterion, generalized
% by Rissanen (GAIC_R), when identifying a
% model with 3 structural indexes (ARMAX, BJ).
%
function [na,nb,nc,GAICR] = GAIC_R3(Lambda,N)
%
%
% Inputs: Lambda # estimated noise variance matrix
% N # size of measured data set
%
% Outputs: na # optimum row order
% nb # optimum column order
% nc # optimum layer order
% GAICR # values of GAIC_R criterion

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Explanation: The 3D array of estimated noise variances


% includes Na rows, Nb columns and Nc layers.
% The GAIC_R criterion is evaluated for each
% element (i,j,k) of matrix. To select the optimum
% structural orders na, nb and nc, the smallest
% of these values is considered. Note that the
% structural indices result by decrementing
% na, nb and nc with 1.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: March 8, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<GAIC_R3>: ' ;
E1 = [FN 'Missing, empty or null N. Empty outputs. Exit.'] ;
E2 = [FN 'Missing or empty Lambda. Empty outputs. Exit.'] ;
E3 = [FN 'No valid model detected. Empty outputs. Exit.'] ;
W1 = [FN 'Inconsistent Lambda. Coarse structure returned.'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
na = [] ;
nb = [] ;
nc = [] ;
GAICR = [] ;
if (nargin < 2)
war_err(E1) ;
return ;
end ;
if (isempty(N))
war_err(E1) ;
return ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

M = abs(fix(N(1))) ;
if (~N)
war_err(E1) ;
return ;
end ;
N = sqrt(N)/N ;
if (nargin < 1)
war_err(E2) ;
return ;
end ;
if (isempty(Lambda))
war_err(E2) ;
return ;
end ;
Lambda = abs(Lambda) ;
Lambda(~Lambda) = eps ;
%
% Evaluating the GAIC_R criterion
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Na,Nb,Nc] = size(Lambda) ;
GAICR = [] ;
Gmin = [] ;
for nc=1:Nc
[Na,Nb,G] = GAIC_R2(Lambda(:,:,nc)*exp(M*(nc-1)),N) ;
na = [na Na] ;
nb = [nb Nb] ;
GAICR = cat(3,GAICR,G) ;
Gmin = [Gmin G(Na,Nb)] ;
end ;
[Gmin,nc] = min(Gmin) ;
na = na(nc) ;
nb = nb(nc) ;
%
% END
%

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% GEN_DATA Module that generates data from a process model


%
function [D,V,P] = gen_data(DP,N,sigma,lambda,bin)
%
% Inputs: DP # IDMODEL object representing the
% process that provides the data
% N # simulation period (250, by default)
% sigma # standard deviation of PRB input
% (1, by default); if null, input inhibited
% lambda # standard deviation of white noise
% (1, by default); if null, noise free
% processes are considered
% bin # flag indicating the type of input:
% 0 -> Gaussian PRB
% 1 -> flip-flop Gaussian PRB (default)
%
% Outputs: D # IDDATA model representing the
% I/O generated data
% V # IDDATA model representing the
% I/O noise generated data
% (white noise as input, colored noise
% as output)
% P # IDMODEL object representing the
% process that provided the data
%
% Explanation: The specified model is stimulated with a PRB
% signal. The generated input and the observed
% output are returned. Note that various processes
% can be used, by setting sigma and/or lambda
% to null.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
%
% Last upgrade: April 9, 2004
%
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% BEGIN
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 5)
bin = 1 ;
end ;
if (isempty(bin))
bin = 1 ;
end ;
bin = abs(sign(bin(1))) ;
if (nargin < 4)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (nargin < 3)
sigma = 1 ;
end ;
if (isempty(sigma))
sigma = 1 ;
end ;
sigma = abs(sigma(1)) ;
if (nargin < 2)
N = 250 ;
end ;
if (isempty(N))
N = 250 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 250 ;
end ;
if (nargin < 1)
DP = idpoly([1 -1.5 0.7],[0 1 0.5],[1 -1 0.2]) ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (isempty(DP))
DP = idpoly([1 -1.5 0.7],[0 1 0.5],[1 -1 0.2]) ;
end ;
if (~isa(DP,'IDMODEL'))
DP = idpoly([1 -1.5 0.7],[0 1 0.5],[1 -1 0.2]) ;
end ;
P = roots(DP.a) ;
P(abs(P)>=1) = 1./P(abs(P)>=1) ; % Correct the stability.
DP.a = poly(P) ;
P = DP ;
%
% Generating the Gaussian white noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambda*randn(N,1) ;
%
% Generating the Gaussian colored noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
V = filter(P.c,1,e) ;
V = iddata(V,e) ; % White noise: V.u
% Colored noise: V.y
%
% Generating the PRB input
% ~~~~~~~~~~~~~~~~~~~~~~~~
u = randn(N,1) ;
u = sigma*(sign(u).^bin).*(u.^(1-bin)) ;
%
% Generating the data
% ~~~~~~~~~~~~~~~~~~~
D = iddata(sim(P,[u e]),u) ;
%
% END
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

%
%CCRRKKVVQQNNWWNN
%
% ISLAB_6A Module that performs comparison between recursive
% identification procedures on an ARMAX process with
% constant parameters.
%
function islab_6a(N,sigma,lambda)
%
% Inputs: N # simulation period (250, by default)
% sigma # standard deviation of PRB input
% (1, by default);
% lambda # standard deviation of white noise
% (1, by default)
%
% Outputs: -------
%
% Explanation: Data generated by an ARMAX process with constant
% parameters are employed to identify its
% parameters through 4 recursive identification
% procedures: RLS, RIV, RPEM, RPLR.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: April 10, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
% BEGIN
%
global FIG ; % Figure number handler
% (to be set before running the routine).
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 3)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

lambda = abs(lambda(1)) ;
if (~lambda)
lambda = 1 ;
end ;
if (nargin < 2)
sigma = 1 ;
end ;
if (isempty(sigma))
sigma = 1 ;
end ;
sigma = abs(sigma(1)) ;
if (nargin < 1)
N = 250 ;
end ;
if (isempty(N))
N = 250 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 250 ;
end ;
%
% Generating the identification data (ARMAX)
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[D,V,P] = gdata_vp(0,N,sigma,lambda,0) ;
%
% Estimating parameters via RLS
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[theta,ypred] = rarx(D,[1 1 1],'ff',1) ;
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(311)
plot(1:N,P.a(2)*ones(N,1),'--r', ...
1:N,theta(:,1),'-b') ;
title('Performances of Recursive Least Squares') ;
ylabel('AR (a)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

subplot(312)
plot(1:N,P.b(2)*ones(N,1),'--r', ...
1:N,theta(:,2),'-b') ;
ylabel('X (b)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(313)
plot(1:N,D.y-ypred,'-m') ;
xlabel('Normalized time') ;
ylabel('Pred. err.') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
FIG=FIG+1 ;
% Estimating parameters via RIV
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[theta,ypred] = riv(D,[1 1 1]) ;
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(311)
plot(1:N,P.a(2)*ones(N,1),'--r', ...
1:N,theta(:,1),'-b') ;
title(['Performances of Recursive Instrumental ’ ...
’Variables']) ;
ylabel('AR (a)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(312)
plot(1:N,P.b(2)*ones(N,1),'--r', ...
1:N,theta(:,2),'-b') ;
ylabel('X (b)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(313)
plot(1:N,D.y-ypred,'-m') ;
xlabel('Normalized time') ;
ylabel('Pred. err.') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
FIG=FIG+1 ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Estimating parameters via RPEM


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[theta,ypred] = rpem(D,[1 1 1 0 0 1],'ff',1) ;
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(411)
plot(1:N,P.a(2)*ones(N,1),'--r', ...
1:N,theta(:,1),'-b') ;
title(['Performances of Recursive ' ...
'Prediction Error Minimization']) ;
ylabel('AR (a)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(412)
plot(1:N,P.b(2)*ones(N,1),'--r', ...
1:N,theta(:,2),'-b') ;
ylabel('X (b)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(413)
plot(1:N,P.c(2)*ones(N,1),'--r', ...
1:N,theta(:,3),'-b') ;
ylabel('MA (c)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(414)
plot(1:N,D.y-ypred,'-m') ;
xlabel('Normalized time') ;
ylabel('Pred. err.') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
FIG=FIG+1 ;
%
% Estimating parameters via RPLR
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[theta,ypred] = rplr(D,[1 1 1 0 0 1],'ff',1) ;
figure(FIG),clf
fig_look(FIG,1.5) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

subplot(411)
plot(1:N,P.a(2)*ones(N,1),'--r', ...
1:N,theta(:,1),'-b') ;
title(['Performances of Recursive ’ ...
’Pseudo-Linear Regression']) ;
ylabel('AR (a)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(412)
plot(1:N,P.b(2)*ones(N,1),'--r', ...
1:N,theta(:,2),'-b') ;
ylabel('X (b)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(413)
plot(1:N,P.c(2)*ones(N,1),'--r', ...
1:N,theta(:,3),'-b') ;
ylabel('MA (c)') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
subplot(414)
plot(1:N,D.y-ypred,'-m') ;
xlabel('Normalized time') ;
ylabel('Pred. err.') ;
V = axis ;
axis([0 N+1 V(3:4)]) ;
%
% END
%

% GDATA_VP Module that generates data from an ARMAX process


% model with constant or variable parameters.
%
function [D,V,P] = gdata_vp(cv,N,sigma,lambda,bin)
%
% Inputs: cv # flag indicating the type of process:
% cv=0 -> constant parameters (default)
% cv=1 -> variable parameters
% N # simulation period (250, by default)

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% sigma # standard deviation of PRB input


% (1, by default) if null, input inhibited
% lambda # standard deviation of white noise
% (1, by default)
% if null, noise free processes considered
% bin # flag indicating the type of input:
% 0 -> Gaussian PRB
% 1 -> flip-flop Gaussian PRB (default)
% Outputs: D # IDDATA object representing the
% I/O generated data
% V # IDDATA object representing the
% I/O noise generated data
% (white noise as input, colored noise
% as output)
% P # IDMODEL object representing the
% process that provided the data
% (see P.a, P.b and P.c for parameters)
%
% Explanation: An ARMAX model with constant or variable
% parameters is stimulated with a PRB signal.
% The generated input and the observed output
% are returned.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: April 9, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Constants
% ~~~~~~~~~
a = -0.7 ; % Constant coefficient of AR part.
b = 0.6 ; % Constant coefficient of X part.
c = -0.9 ; % Constant coefficient of MA part.
oa = 10*pi ; % Basic pulsation of AR part.
ob = 4*pi ; % Basic pulsation of X part.
oc = 18*pi ; % Basic pulsation of MA part.

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 5)
bin = 1 ;
end ;
if (isempty(bin))
bin = 1 ;
end ;
bin = abs(sign(bin(1))) ;
if (nargin < 4)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (nargin < 3)
sigma = 1 ;
end ;
if (isempty(sigma))
sigma = 1 ;
end ;
sigma = abs(sigma(1)) ;
if (nargin < 2)
N = 250 ;
end ;
if (isempty(N))
N = 250 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 250 ;
end ;
if (nargin < 1)
cv = 0 ;
end ;
if (isempty(cv))
cv = 0 ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

cv = cv(1) ;
%
% Building the process with constant parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P = idpoly([1 a],[0 b],[1 c]) ;
%
% Generating the Gaussian white noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambda*randn(N,1) ;
%
% Generating the PRB input
% ~~~~~~~~~~~~~~~~~~~~~~~~
u = randn(N,1) ;
u = sigma*(sign(u).^bin).*(u.^(1-bin)) ;
%
% Generating the data
% ~~~~~~~~~~~~~~~~~~~
if (cv) % Case: variable parameters.
n = (1:N)/N ; % Define the variable parameters.
a = a*cos(oa*n) ;
b = b*sign(cos(ob*n)) ;
n = n*oc ;
c = c*sin(n)./n ;
V = e(1) ;
D = V ;
for n=2:N % Generate the noise & output.
V = [V ; e(n)+c(n)*e(n-1)] ;
D = [D ; -a(n)*D(n-1)+b(n)*u(n-1)+e(n)+c(n)*e(n-1)] ;
end ;
D = iddata(D,u) ;
P.a = [1 a] ;
P.b = [0 b] ;
P.c = [1 c] ;
Else % Case: constant parameters.
V = filter(P.c,1,e) ; % Generatng the colored noise.
D = iddata(sim(P,[u e]),u) ; % Output data.
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Recording the noise.


V = iddata(V,e) ; % White noise: V.u
% Colored noise: V.y
%
% END
%
% RIV Implements the Recursive Instrumental Variables Method
% with exponential window applied on prediction errors.
%
function [theta,ypred,P,phi,z] = ...
riv(D,si,f,lambda,theta0,P0,phi0,z0)
%
% Inputs: D # IDDATA object including the identification
% data (which have to be ARX modelled)
% si # structural indices vector [na nb nk]
% f # the vector of instruments (D.u, by default)
% (must have the same length as D.u,
% otherwise it is cut or zero-padded,
% whichever applies)
% lambda # forgetting factor (1, by default)
% theta0 # initial guess of parameters vector
% (null, by default)
% P0 # initial guess of main matrix inverse
% (unit, by default)
% phi0 # initial guess of regressors vector
% (null, by default)
% z0 # initial guess of instrumental vector
% (null, by default)
%
% Outputs: theta # matrix including on each row the estimated
% parameters [a b] corresponding to a
% sampling instant; the number of rows equals
% the length of D.u (or f)
% ypred # predicted outpud when using the estimated
% parameters theta
% P # final value of main matrix inverse
% phi # final value of regressors vector
% z # final value of instrumental vector

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Explanation: An ARX model with variable parameters is


% estimated through the Recursive Instrumental
% Variables Method starting from experimental
% data. The prediction errors are exponentially
% windowed in this aim.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
%
% Last upgrade: April 10, 2004
%
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<RIV>: ' ;
EX = 'Empty outputs. Exit.' ;
E1 = [FN 'Missing or empty measured data. ' EX] ;
E2 = [FN 'Unrecognized data set ' ...
'(not an IDDATA object). ' EX] ;
E3 = [FN 'Inconsistent measured data. ' EX] ;
E4 = [FN 'Missing or empty structural indices. ' EX] ;
E5 = [FN 'Inconsistent structural indices. ' EX] ;
E6 = [FN 'Null forgetting factor. ' EX] ;
E7 = [FN 'Wrong size of P0 matrix. ' EX] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
theta = [] ;
ypred = [] ;
P = [] ;
phi = [] ;
z = [] ;
if (nargin < 1)
war_err(E1) ;
return ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (isempty(D))
war_err(E1) ;
return ;
end ;
if (~isa(D,'IDDATA'))
war_err(E2) ;
return ;
end ;
if (isempty(D.u))
war_err(E3) ;
return ;
end ;
if (nargin < 2)
war_err(E4) ;
return ;
end ;
if (isempty(si))
war_err(E4) ;
return ;
end ;
si = vectoriz(si) ;
if (length(si) < 3)
war_err(E5) ;
return ;
end ;
si = abs(round(si(1:3))) ;
si(3) = max(1,si(3)) ;
na = si(1) ;
nb = si(2) ;
nk = si(3) ;
if (nargin < 3)
f = D.u ;
end ;
if (isempty(f))
f = D.u ;
end ;
f = vectoriz(f)' ;
n = length(f) ;
N = length(D.u) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

n = min(n,N) ;
f = [f(1:n) ; zeros(N-n,1)];
if (nargin < 4)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (~lambda)
war_err(E6) ;
return ;
end ;
if (lambda>1)
lambda = 1/lambda ;
end ;
k = na+nb+nk-1 ;
if (nargin < 5)
theta0 = zeros(k,1) ;
end ;
if (isempty(theta0))
theta0 = zeros(k,1) ;
end ;
theta0 = vectoriz(theta0)' ;
n = min(length(theta0),k) ;
theta0 = [theta0(1:n) zeros(k-n,1)] ;
if (nargin < 6)
P0 = eye(k) ;
end ;
if (isempty(P0))
P0 = eye(k) ;
end ;
P0 = P0(:,:) ;
if ((size(P0,1)-k) | (size(P0,2)-k))
war_err(E7) ;
return ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (nargin < 7)
phi0 = zeros(k,1) ;
end ;
if (isempty(phi0))
phi0 = zeros(k,1) ;
end ;
phi0 = vectoriz(phi0)' ;
n = min(length(phi0),k) ;
phi0 = [phi0(1:n) zeros(k-n,1)] ;
if (nargin < 8)
z0 = zeros(k,1) ;
end ;
if (isempty(z0))
z0 = zeros(k,1) ;
end ;
z0 = vectoriz(z0)' ;
n = min(length(z0),k) ;
z0 = [z0(1:n) zeros(k-n,1)] ;
%
% Centering the data
% ~~~~~~~~~~~~~~~~~~
D.y = D.y - mean(D.y) ;
D.u = D.u - mean(D.u) ;
f = f - mean(f) ;
%
% Recursive identification and simulation
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
nb = nb+nk-1 ; % Initialization.
D = iddata([zeros(nb,1) ; -phi0(na:-1:1) ; D.y], ...
[zeros(na,1) ; phi0(k:-1:(na+1)) ; D.u]) ;
f = [z0(k:-1:1) ; f] ;
phi = [-D.y((k-1):-1:(nb+1)) ; 0 ; D.u((k-1):-1:(na+1)) ; 0] ;
z = [f((k-1):-1:1) ; 0] ;
P = P0 ;
si = theta0 ;
for n=(k+1):(k+N) % Estimation and simulation.
phi = [-D.y(n-1) ; phi(1:(na-1)) ; ...
D.u(n-1) ; phi((na+1):(k-1))] ;
z = [f(n-1) ; z(1:(k-1))] ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

nk = P*z ;
nk = nk/(lambda+phi'*nk) ; % Gain vector.
P = (P-nk*phi'*P)/lambda ; % Next matrix.
ypred = [ypred ; phi'*si] ; % Predicted output.
si = si + nk*(D.y(n)-ypred(end)) ; % Upgrade parameters.
theta = [theta ; si'] ; % Save parameters.
end ;
%
% END
%

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

%
%CCRRKKVVQQNNWWNN
%
% ISLAB_7A Module that performs off-line identification of
% an ARMAX model approximating a general purpose
% model around a specified frequency.
%
function [D,F,M] = islab_7a(N,sigma,lambda)
%
% Inputs: N # simulation period (250, by default)
% sigma # standard deviation of PRB input
% (1, by default);
% lambda # standard deviation of white noise
% (1, by default)
%
% Outputs: D # IDDATA object representing the I/O data
% to be employed within an on-line
% identification procedure
% F # structure representing the Butterworth
% filter applied on the PRB input signal
% in order to provide the data D
% F.A -> filter denominator
% F.B -> filter numerator
% F.fc -> cut-off frequency index
% (scalar or 2-length vector
% in range (0,1) - see MATLAB
% function BUTTER)
% M # IDMODEL object representing the ARMAX
% identified using the off-line PEM
%
% Explanation: Data generated by a general purpose model are
% employed to identify an approximative ARMAX
% model around a specified frequency, through
% the off-line PEM. The method involves designing
% of a Butterworth filter that has to be applied
% on the PRB input signal. The data resulted when
% stimulating the general model with the filtered
% data are returned, as well as the filter
% characteristics and the structural indices of
% the off-line identified ARMAX model.

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Author: Dan Stefanoiu (*)


% Revised: Dan Stefanoiu (*)
% Last upgrade: April 10, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
% BEGIN
%
global FIG ; % Figure number handler
% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~
K = 7 ; % Butterworth filter order.
L = 2^10 ; % Frequency resolution.
nr = 100 ; % Number of realizations.
% Messages
% ~~~~~~~~
FN = '<ISLAB_7A>: ' ;
NFN = length(FN) ;
PK = [blanks(70) '<Press a key>'] ;
M1 = [FN 'Select the type of Butterworth filter ' ...
'[1=low-pass / 2=band-pass]: '] ;
M2 = [blanks(NFN) '# Butterworth filter type: %s-pass.'] ;
M3 = [FN 'Use the cursor and your mouse ' ...
'to set the cut-off pulsations.'] ;
M4 = [blanks(NFN) '# Cut-off pulsation%s [rad]: %g %g'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 3)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (~lambda)
lambda = 1 ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (nargin < 2)
sigma = 1 ;
end ;
if (isempty(sigma))
sigma = 1 ;
end ;
sigma = abs(sigma(1)) ;
if (nargin < 1)
N = 250 ;
end ;
if (isempty(N))
N = 250 ;
end ;
N = abs(fix(N(1))) ;
if (~N)
N = 250 ;
end ;
%
% Generate the raw identification data
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Fu = [] ; % Initialization.
Fy = [] ;
u = sigma*randn(N,nr) ; % Gaussian PRB inputs.
for n=1:nr
% Power spectral density of input.
Fu = [Fu abs(fft(xcov(u(:,n))))] ;
D = gdata_cp(u(:,n),lambda) ; % Output data.
% Power spectral density of output.
Fy = [Fy abs(fft(xcov(D.y)))] ;
end ;
%
% Evaluate the process spectrum
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Fu = Fu(1:N,:) ; % Use symmetry to reduce size.
Fy = Fy(1:N,:) ;
Fu(Fu<eps) = eps ; % Try to avoid division by zero.
F = Fy./Fu ; % Noised spectrum.
F = mean(F') ; % Averaged spectrum.
F(F<eps) = eps ; % Conversion to deciBells.

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

F = dB(F)/2 ;
omega = pi*(0:(N-1))/N ; % Normalized pulsation axis.
%
% Plot the process spectrum
% ~~~~~~~~~~~~~~~~~~~~~~~~~
figure(FIG),clf
fig_look(FIG,1.5) ;
plot(omega,F,'-b') ;
n = scaling(F,0.05) ; % Re-scale the axes.
axis([0 pi n]) ;
grid ;
title('Raw spectrum of data provider process') ;
xlabel('Normalized pulsation [rad]') ;
ylabel('Spectral power [dB]') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
text(2.25,n(1)-0.08*(n(2)-n(1)),'<Go to command window>') ;
FIG = FIG+1 ;
%
% Select the cut-off pulsation(s) of filter
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
n = input(M1) ; % Ask for filter type.
if (isempty(n))
n = 2 ; % Band-pass filter by default.
end ;
n = abs(round(n(1))) ;
if (n<2)
n = 1 ;
M1 = 'low' ;
else
n = 2 ;
M1 = 'band' ;
end ;
war_err(sprintf(M2,M1)) ; % Confirm filter type.
war_err(M3) ;
disp(PK) ;
pause ;
[omega,Fy] = ginput(n) ; % Ask for cut-off pulsation(s).
omega = sort(omega) ;
M1 = [] ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (n>1)
M1 = 's' ;
end ;
war_err(sprintf(M4,M1,omega)) ; % Display cut-off pulsation(s).
%
% Design the filter
% ~~~~~~~~~~~~~~~~~
F.fc = omega/pi ; % Record cut-off index.
[F.B F.A] = butter(K,F.fc) ;% Design filter.
%
% Plot filter characteristics
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~
omega = pi*(0:(L-1))/L ; % Set normalized pulsation axis.
% Evaluate magnitude Fy and phase Fu.
[Fy,Fu,omega] = dbode(F.B,F.A,1,omega) ;
Fu = pi*Fu/180 ; % Conversion of phase to radians.
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(211)
plot(omega,Fy,'-b') ;
grid ;
axis([0 pi -0.05 1.05]) ;
M1 = 'Frequency characteristics of ' ;
M3 = '-pass Butterworth filter of order K = ' ;
if (n<2)
M2 = 'low' ;
else
M2 = 'band' ;
end ;
title([M1 M2 M3 int2str(K) '.']) ;
ylabel('Magnitude') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
text(1.05*pi*F.fc(n),0.5, ...
['\omega_c = ' sprintf('%4.2f',pi*F.fc(n))]) ;
if (n>1)
text(pi*F.fc(1),0.5, ...
['\omega_c = ' sprintf('%4.2f',pi*F.fc(1))]) ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

subplot(212)
set(FIG,'DefaultTextHorizontalAlignment','center') ;
plot(omega,Fu,'-m') ;
grid ;
n = scaling(Fu,0.05) ;
axis([0 pi n]) ;
xlabel('Normalized pulsation') ;
ylabel('Phase [rad]') ;
FIG = FIG+1 ;
%
% Provide the identification data
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
u = sigma*randn(N,1) ; % Unfiltered input.
u = filter(F.B,F.A,u) ; % Filtered input.
[D,V,P] = gdata_cp(u,lambda) ; % Corresponding I/O data.
%
% Off-line identification of ARMAX model
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
M = pem(D) ; % Using PEM to provide a
% general state-space model.
[M1,M2,M3] = polydata(M) ; % Convert the model to
% polynomials.
M = idpoly(M1,M2,M3) ; % Convert polynomials to
% identification model object.
%
% Simulate the ARMAX model
% ~~~~~~~~~~~~~~~~~~~~~~~~
Fy = sim(M,[D.u V.u]) ;
%
% Compute output power spectral densities
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Fy = abs(fft(xcov(Fy))) ; % Simulated output.
Fy = Fy(1:N) ; % Use symmetry to reduce size.
Fy(Fy<eps) = eps ; % Try to avoid division by zero.
Fy = dB(Fy) ; % Conversion to deciBells.
Fu = abs(fft(xcov(D.y))) ; % Measured output.
Fu = Fu(1:N) ; % Use symmetry to reduce size.
Fu(Fu<eps) = eps ; % Try to avoid division by zero.
Fu = dB(Fu) ; % Conversion to deciBells.

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

%
% Compare power spectral densities (full bandwidth)
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
omega = pi*(0:(N-1))/N ; % Set normalized pulsation axis.
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(311)
plot(omega,Fu,'-r') ;
u = scaling(Fu,0.05) ;
axis([0 pi u]) ;
title(['Performances of ARMAX model: ' ...
'output psd \phi_y (full bandwidth).']) ;
ylabel('Measured [dB]') ;
subplot(312)
plot(omega,Fy,'-b') ;
u = scaling(Fy,0.05) ;
axis([0 pi u]) ;
ylabel('Simulated [dB]') ;
subplot(313)
plot(omega,Fu-Fy,'-m') ;
u = scaling(Fu-Fy,0.05) ;
axis([0 pi u]) ;
xlabel('Normalized pulsation [rad]') ;
ylabel('Error [dB]') ;
FIG = FIG+1 ;
%
% Compare power spectral densities (filter bandwidth)
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
n = (omega>=(F.fc(1)*pi)) ; % Isolate the filter bandwidth.
if (length(F.fc>1))
n = n & (omega<=(F.fc(2)*pi)) ;
end ;
omega = omega(n) ;
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(311)
plot(omega,Fu(n),'-r') ;
u = scaling(Fu(n),0.05) ;
axis([omega(1) omega(end) u]) ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

title(['Performances of ARMAX model: ' ...


'output psd \phi_y (filter bandwidth).']) ;
ylabel('Measured [dB]') ;
subplot(312)
plot(omega,Fy(n),'-b') ;
u = scaling(Fy(n),0.05) ;
axis([omega(1) omega(end) u]) ;
ylabel('Simulated [dB]') ;
subplot(313)
plot(omega,Fu(n)-Fy(n),'-m') ;
u = scaling(Fu(n)-Fy(n),0.05) ;
axis([omega(1) omega(end) u]) ;
xlabel('Normalized pulsation [rad]') ;
ylabel('Error [dB]') ;
FIG = FIG+1 ;
%
% END
%
% ISLAB_7C Module that performs off-line identification of
% physical parameters of a DC engine (gain and
% time constant). The parameters are constant.
%
function [F,D,M] = islab_7c(mt,K0,T0,Tmax,Ts,U,lambda)
%
% Inputs: mt # model type:
% 0 -> OE (default)
% 1 -> ARX
% K0 # constant gain (4, by default)
% T0 # constant time constant (0.5 s, by default)
% Tmax # simulation duration (80 s, by default)
% Ts # sampling period (0.1 s, by default)
% U # amplitude of input square wave
% (0.5, by default)
% lambda # standard deviation of white noise
% (1, by default)
%
% Outputs: F # structure representing the estimated
% physical parameters:
% F.K -> gain

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% F.T -> time constant


% D # IDDATA object representing the I/O data
% employed in identification
% M # IDMODEL object representing the estimated
% discrete time model
%
% Explanation: A second order continuous transfer function
% with a null pole, gain K and time constant T
% (the model of a DC engine) is stimulated with
% a square wave in order to provide identification
% data. Constant parameters K and T are identified
% by discretizing the transfer function.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: April 29, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
global FIG ; % Figure number handler
% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~
K = 7 ; % Butterworth filter order.
L = 2^10 ; % Frequency resolution.
nr = 100 ; % Number of realizations.
% Messages
% ~~~~~~~~
FN = '<ISLAB_7C>: ' ;
NFN = length(FN) ;
PK = [blanks(70) '<Press a key>'] ;
M1 = [FN 'Physical parameters:'] ;
M2 = [blanks(NFN+7) 'True' blanks(8) 'Estimated'] ;
M3 = [blanks(NFN) 'K: %8.4f' blanks(6) '%8.4f'] ;
M4 = [blanks(NFN) 'T: %8.4f' blanks(6) '%8.4f'] ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 7)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (~lambda)
lambda = 1 ;
end ;
if (nargin < 6)
U = 0.5 ;
end ;
if (isempty(U))
U = 0.5 ;
end ;
U = U(1) ;
if (abs(U)<eps)
U = 0.5 ;
end ;
if (nargin < 5)
Ts = 0.1 ;
end ;
if (isempty(Ts))
Ts = 0.1 ;
end ;
Ts = abs(Ts(1)) ;
if (Ts<eps)
Ts = 0.1 ;
end ;
if (nargin < 4)
Tmax = 80 ;
end ;
if (isempty(Ts))
Tmax = 80 ;
end ;
Tmax = abs(Tmax(1)) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (Tmax<eps)
Tmax = 80 ;
end ;
Tmax = max(250*Ts,Tmax) ;
if (nargin < 3)
T0 = 0.5 ;
end ;
if (isempty(T0))
T0 = 0.5 ;
end ;
T0 = T0(1) ;
if (abs(T0)<eps)
T0 = 0.5 ;
end ;
if (nargin < 2)
K0 = 4 ;
end ;
if (isempty(K0))
K0 = 4 ;
end ;
K0 = K0(1) ;
if (abs(K0)<eps)
K0 = 4 ;
end ;
if (nargin < 1)
mt = 0 ;
end ;
if (isempty(mt))
mt = 0 ;
end ;
mt = abs(round(mt(1))) ;
%
% Generate identification data
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[D,V] = gdata_fp(0,K0,T0,Tmax,Ts,U,lambda) ;
%
% Estimate discrete time parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (~mt)
M = oe(D,[2 2 1]) ; % Model of tipe OE.

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

else
M = arx(D,[2 2 1]) ; % Model of type ARX.
end ;
%
% Estimate physical parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (~mt) % OE model.
F.K = sum(M.b)/(1-M.f(3))/Ts ;
F.T = Ts*(M.f(3)*M.b(2)+M.b(3))/sum(M.b)/(1-M.f(3)) ;
% F.T = -Ts/log(M.f(3)) ;
else % ARX model.
F.K = sum(M.b)/(1-M.a(3))/Ts ;
F.T = Ts*(M.a(3)*M.b(2)+M.b(3))/sum(M.b)/(1-M.a(3)) ;
% F.T = -Ts/log(M.a(3)) ;
end ;
%
% Display physical parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~
war_err(M1) ;
disp(M2) ;
disp(sprintf(M3,K0,F.K)) ;
disp(sprintf(M4,T0,F.T)) ;
war_err(PK) ;
pause ;
%
% Plot I/O data
% ~~~~~~~~~~~~~
Tmax = Ts*round(Tmax/Ts) ; % Correct Tmax.
t = 0:Ts:Tmax ; % Set time axis.
figure(FIG),clf
fig_look(FIG,1.5) ;
plot(t,D.u,'-b',t,D.y,'-r') ;
FN = scaling([D.u D.y]) ; % Re-scale the axes.
axis([0 Tmax FN]) ;
title('Input-output data provided by a DC engine.') ;
xlabel('Time [s]') ;
ylabel('Magnitude') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('input (square wave)','output',0) ;
FIG = FIG+1 ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Plot I/O simulated data


% ~~~~~~~~~~~~~~~~~~~~~~~
V.y = sim(M,[D.u zeros(size(D.u))]) ;
figure(FIG),clf
fig_look(FIG,1.5) ;
plot(t,V.y,'-b',t,D.y,'-r',t,V.y,'-b') ;
FN = scaling([V.y D.y]) ; % Re-scale the axes.
axis([0 Tmax FN]) ;
title(['Output data provided by a DC engine ' ...
'and its discrete model.']) ;
xlabel('Time [s]') ;
ylabel('Magnitude') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('simulated output','measured output',0) ;
FIG = FIG+1 ;
%
% END
%
%
% ISLAB_7E Module that performs on-line identification of
% physical parameters of a DC engine (gain and
% time constant). The parameters are variable.
%
function [F,ID,SD] = islab_7e(mt,K0,T0,Tmax,Ts,U,lambda)
%
% Inputs: mt # model type:
% 0 -> OE (default)
% 1 -> ARX
% K0 # constant gain (4, by default)
% T0 # constant time constant (0.5 s, by default)
% Tmax # simulation duration (80 s, by default)
% Ts # sampling period (0.1 s, by default)
% U # amplitude of input square wave
% (0.5, by default)
% lambda # standard deviation of white noise
% (1, by default)
%
% Outputs: F # structure representing the estimated
% physical parameters:

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% F.K -> gain


% F.T -> time constant
% ID # IDDATA object representing the I/O data
% employed in identification
% SD # IDDATA object representing the simulated
% data provided by the discrete transfer
% functions, within SD.y (output) and
% SD.u (noise); the input is saved
% within ID.u.
%
% Explanation: A second order continuous transfer function
% with a null pole, gain K and time constant T
% (the model of a DC engine) is stimulated with
% a square wave in order to provide identification
% data. Variable parameters K and T are
% identified and pursued by discretizing the
% transfer function.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: April 29, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
global FIG ; % Figure number handler
% (to be set before running the routine).
%
% Constants
% ~~~~~~~~~
cv = 1 ; % Flag indicating the type of
% physical parameters:
% cv = 0 -> constant parameters
% cv = 1 -> variable parameters
%
% Messages
% ~~~~~~~~
FN = '<ISLAB_7E>: ' ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

WB = [FN 'Recursive estimation of parameters. ' ...


'This may take a minute. Please wait ...'] ;
WE = [blanks(length(FN)) '... Done.'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 7)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (~lambda)
lambda = 1 ;
end ;
if (nargin < 6)
U = 0.5 ;
end ;
if (isempty(U))
U = 0.5 ;
end ;
U = U(1) ;
if (abs(U)<eps)
U = 0.5 ;
end ;
if (nargin < 5)
Ts = 0.1 ;
end ;
if (isempty(Ts))
Ts = 0.1 ;
end ;
Ts = abs(Ts(1)) ;
if (Ts<eps)
Ts = 0.1 ;
end ;
if (nargin < 4)
Tmax = 80 ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (isempty(Ts))
Tmax = 80 ;
end ;
Tmax = abs(Tmax(1)) ;
if (Tmax<eps)
Tmax = 80 ;
end ;
Tmax = max(250*Ts,Tmax) ;
if (nargin < 3)
T0 = 0.5 ;
end ;
if (isempty(T0))
T0 = 0.5 ;
end ;
T0 = T0(1) ;
if (abs(T0)<eps)
T0 = 0.5 ;
end ;
if (nargin < 2)
K0 = 4 ;
end ;
if (isempty(K0))
K0 = 4 ;
end ;
K0 = K0(1) ;
if (abs(K0)<eps)
K0 = 4 ;
end ;
if (nargin < 1)
mt = 0 ;
end ;
if (isempty(mt))
mt = 0 ;
end ;
mt = abs(round(mt(1))) ;
%
% Generate identification data
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
war_err(WB) ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

[ID,V,P] = gdata_fp(cv,K0,T0,Tmax,Ts,U,lambda) ;
if (~cv)
FN = ones(1,length(ID.y)) ;
P.num{1} = K0*FN ;
P.den{1} = T0*FN ;
end ;
%
% Estimate and pursue discrete time parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (~mt) % Model of tipe OE.
[theta,SD] = roe(ID,[2 2 1],'ff',0.999) ;
theta = theta(:,[3 4 1 2]) ; % theta = [B|F]->[F|B].
else % Model of type ARX.
[theta,SD] = rarx(ID,[2 2 1],'ff',0.999) ;
% theta = [A|B].
end ;
war_err(WE) ;
SD = iddata(SD,V.u,Ts) ; % Pack simulation data.
%
% Estimate physical parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
F.K = (theta(:,3)+theta(:,4))./(1-theta(:,2))/Ts ;
F.T = Ts*(theta(:,2).*theta(:,3)+theta(:,4))./ ...
(theta(:,3)+theta(:,4))./(1-theta(:,2)) ;
% F.T = -Ts./log(theta(:,2)) ;
%
% Plot I/O data
% ~~~~~~~~~~~~~
Tmax = Ts*round(Tmax/Ts) ; % Correct Tmax.
t = 0:Ts:Tmax ; % Set time axis.
figure(FIG),clf
fig_look(FIG,1.5) ;
plot(t,ID.u,'-b',t,ID.y,'-r') ;
FN = scaling([ID.u ID.y]) ; % Re-scale the axes.
axis([0 Tmax FN]) ;
title('Input-output data provided by a DC engine.') ;
xlabel('Time [s]') ;
ylabel('Magnitude') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

legend('input (square wave)','output',0) ;


FIG = FIG+1 ;
%
% Plot I/O simulated data
% ~~~~~~~~~~~~~~~~~~~~~~~
figure(FIG),clf
fig_look(FIG,1.5) ;
plot(t,SD.y,'-b',t,ID.y,'-r',t,SD.y,'-b') ;
FN = scaling([SD.y ID.y]) ; % Re-scale the axes.
axis([0 Tmax FN]) ;
title(['Output data provided by a DC engine ' ...
'and its discrete model.']) ;
xlabel('Time [s]') ;
ylabel('Magnitude') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('simulated output','measured output',0) ;
FIG = FIG+1 ;
%
% Plot physical parameters variation
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(211)
plot(t,F.K,'-b',t,P.num{1},'-r') ;
FN = scaling([F.K P.num{1}']) ; % Re-scale the axes.
axis([0 Tmax FN]) ;
title(['Physical parameters variation (DC engine).']) ;
xlabel('Time [s]') ;
ylabel('Gain K') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('estimated','true',0) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
subplot(212)
plot(t,F.T,'-b',t,P.den{1},'-r') ;
FN = scaling([F.T P.den{1}']) ; % Re-scale the axes.
axis([0 Tmax FN]) ;
ylabel('Time constant T [s]') ;
xlabel('Time [s]') ;
FIG = FIG+1 ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% Zoom on physical parameters variation (steady-state)


% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%WE = (t>(0.1*Tmax/T0)) ;
WE = (t>(0.5*Tmax)) ;
t = t(WE) ;
figure(FIG),clf
fig_look(FIG,1.5) ;
subplot(211)
plot(t,F.K(WE),'-b',t,P.num{1}(WE),'-r') ;
% Re-scale the axes.
FN = scaling([F.K(WE) P.num{1}(WE)']) ;
axis([t(1) Tmax FN]) ;
title(['Physical parameters variation – ' ...
'steady-state (DC engine).']) ;
xlabel('Time [s]') ;
ylabel('Gain K') ;
set(FIG,'DefaultTextHorizontalAlignment','left') ;
legend('estimated','true',0) ;
set(FIG,'DefaultTextHorizontalAlignment','center') ;
subplot(212)
plot(t,F.T(WE),'-b',t,P.den{1}(WE),'-r') ;
% Re-scale the axes.
FN = scaling([F.T(WE) P.den{1}(WE)']) ;
axis([t(1) Tmax FN]) ;
ylabel('Time constant T [s]') ;
xlabel('Time [s]') ;
FIG = FIG+1 ;
%
% END
%
% GDATA_FP Module that generates data from the physical model
% of a DC engine with constant or
% variable parameters.
%
function [D,V,P] = gdata_fp(cv,K0,T0,Tmax,Ts,U,lambda)
%
% Inputs: cv # flag indicating the type of process:
% cv=0 -> constant parameters (default)
% cv=1 -> variable parameters

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% K0 # constant gain (4, by default)


% T0 # constant time constant (0.5 s, by default)
% Tmax # duration of simulation period
% (80 s, by default)
% Ts # sampling period (0.1 s, by default)
% U # Amplitude of square wave input
% (0.5, by default)
% lambda # standard deviation of white noise
% (1, by default); if null, a noise
% free process is considered
%
% Outputs: D # IDDATA object representing the
% I/O generated data
% V # IDDATA object representing the
% I/O noise generated data
% (white noise as input, colored noise
% as output)
% P # LTI-TF object representing the
% process that provided the data
% (see P.num, P.den for transfer
% function polynomials in case the
% parameters K and T are constant;
% otherwise, P.num{1}=K(t), while
% P.den{1}=T(t))
%
% Explanation: The continuous model of a DC engine is expressed
% by a second order transfer function with a null
% pole, gain K and time constant T:
% K
% H(s) = --------- .
% s(1+sT)
% The model with constant or variable parameters
% is employed to generate the identification data.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: April 29, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% BEGIN
%
% Constants
% ~~~~~~~~~
nu = 1/7 ; % Fraction representing the ratio between
% the period of input square wave and
% the simulation period.
a = [3 -3 1] ; % Coefficients of parabola that
% defines the variable gain K:
% K(t) = K0*a*
% [t^2 ; t*Tmax ; Tmax^2]/(Tmax^2).
b = [0.5 10*pi] ; % Relative amplitude (b(1)) and
% pulsation of harmonic wave (b(2))
% that defines the variable
% time constant T:
% T(t) = T0*(1+b(1)*sin(b(2)*t/Tmax)).
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 7)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (nargin < 6)
U = 0.5 ;
end ;
if (isempty(U))
U = 0.5 ;
end ;
U = U(1) ;
if (abs(U)<eps)
U = 0.5 ;
end ;
if (nargin < 5)
Ts = 0.1 ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (isempty(Ts))
Ts = 0.1 ;
end ;
Ts = abs(Ts(1)) ;
if (Ts<eps)
Ts = 0.1 ;
end ;
if (nargin < 4)
Tmax = 80 ;
end ;
if (isempty(Ts))
Tmax = 80 ;
end ;
Tmax = abs(Tmax(1)) ;
if (Tmax<eps)
Tmax = 80 ;
end ;
Tmax = max(250*Ts,Tmax) ;
if (nargin < 3)
T0 = 0.5 ;
end ;
if (isempty(T0))
T0 = 0.5 ;
end ;
T0 = T0(1) ;
if (abs(T0)<eps)
T0 = 0.5 ;
end ;
if (nargin < 2)
K0 = 4 ;
end ;
if (isempty(K0))
K0 = 4 ;
end ;
K0 = K0(1) ;
if (abs(K0)<eps)
K0 = 4 ;
end ;

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

if (nargin < 1)
cv = 0 ;
end ;
if (isempty(cv))
cv = 0 ;
end ;
cv = cv(1) ;
%
% Building the continuous model with constant parameters
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P = tf(K0,[T0 1 0],0) ;
%
% Generating the Gaussian white noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
N = round(Tmax/Ts) ; % Set the number of samples.
Tmax = N*Ts ; % Correct Tmax.
N = N+1 ; % Correct number of samples.
e = lambda*randn(N,1) ;
%
% Generating the square wave input
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D = ones(round(N*nu/2),1) ; % Set half period wave.
U = U*[D ; -D] ; % Set input on whole period.
u = kron(ones(fix(1/nu),1),U) ; % Set almost all input.
u = [u ; U] ; % Complete the input.
u = u(1:N) ; % Initial null values.
%
% Generating the data
% ~~~~~~~~~~~~~~~~~~~
t = 0:Ts:Tmax ; % Set time axis.
if (cv) % Case: variable parameters.
n = t/Tmax ; % Set the normalized time.
% Variable gain.
K = K0*(a(1)*(n.^2)+a(2)*n+a(3)) ;
T = T0*(1+b(1)*sin(b(2)*n)) ;% Variable time constant.
u = [0 ; 0 ; u] ; % Initial null input.
D = [0 ; 0] ; % Initial null output.

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

for n=1:N % Generate the noisy output.


% Continuous time
% transfer function.
V = tf(K(n),[T(n) 1 0],0) ;
V = c2d(V,Ts) ; % Discretizing
% the transfer function.
% Output ideal data.
V = V.num{1}*[0 ; u(n+1) ; u(n)]- ...
V.den{1}*[0 ; D(n+1) ; D(n)] ;
D = [D ; V] ;
end ;
u(1:2) = [] ; % Remove initial input.
D(1:2) = [] ; % Remove initial output.
P.num{1} = K ; % Record K variation.
P.den{1} = T ; % Record T variation.
Else % Case: constant parameters.
D = lsim(P,u,t) ; % Generate the ideal output.
end ;
D = D+e ; % Output noisy data.
D = iddata(D,u,Ts) ; % Pack input-output data.
V = iddata(e,e,Ts) ; % Record the noise.
% White noise: V.u or V.y.
%
% END
%
% GDATA_VP Module that generates data from a general
% (complex) model of identification.
%
function [D,V,P] = gdata_cp(u,lambda)
%
% Inputs: u # input signal (by default, u is a
% Gaussian PRB signal of length 250)
% lambda # standard deviation of white noise
% (1, by default); if null, the noise free
% process considered
%
% Outputs: D # IDDATA object representing the
% I/O generated data
% V # IDDATA object representing the

%&
/KPKUKOWNCVQCTGĩKTWVKPG/#6.#$RGPVTW%CRKVQNWN

% I/O noise generated data


% (white noise as input, colored noise
% as output)
% P # IDMODEL object representing the
% process that provided the data (see P.a,
% P.b, P.c, P.d and P.f for parameters)
%
% Explanation: A general purpose identification model
% is stimulated with a given or PRB signal.
% The generated input and the observed output
% are returned.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: April 14, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Constants
% ~~~~~~~~~
a = [1 -1.5 0.9] ; % Coefficients of A.
b = [0 0 1 -1.3 0.8] ; % Coefficients of B.
c = [1 -1 0.2 0 -0.18] ; % Coefficients of C.
d = [1 -2 1.85 -0.65] ; % Coefficients of D.
f = [1 0 0.9] ; % Coefficients of F.
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 2)
lambda = 1 ;
end ;
if (isempty(lambda))
lambda = 1 ;
end ;
lambda = abs(lambda(1)) ;
if (nargin < 1)
u = randn(250,1) ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (isempty(u))
u = randn(250,1) ;
end ;
u = vectoriz(u)' ;
N = length(u) ;
%
% Building the process
% ~~~~~~~~~~~~~~~~~~~~
P = idpoly(a,b,c,d,f) ;
%
% Generating the Gaussian white noise
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
e = lambda*randn(N,1) ;
%
% Generating the data
% ~~~~~~~~~~~~~~~~~~~
V = filter(P.c,P.d,e) ; % Generate the colored noise.
V = filter(1,P.a,V) ;
V = iddata(V,e) ; % Record the noise.
% White noise: V.u
% Colored noise: V.y
D = iddata(sim(P,[u e]),u) ; % Output data.
%
% END
%

%&
4WVKPG/#6.#$FGW\IGPGTCN

4
4WWVVKKPPGG/
/###666...###$$$FFGGWW\\IIGGPPGGTTCCNN
%
% FIG_LOOK Controls the appearance of a MATLAB figure.
%
function fig_look(H,lw)
%
% Inputs: H # number of figure handle
% (current figure number by default)
% lw # line width (pt) of graphics
% 0.5 pt, by default);
%
% Outputs: -------
%
% Explanation: Some parameters that change the general aspect
% (look) of the figure with handle H may be
% changed. If H is missing or empty, the current
% figure is affected. The second parameter, if
% specified and non-empty stands for the desired
% line width of graphics.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: February 5, 2003
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
global FIG ; % Figure number handler
% (to be set before running the routine).
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 1)
H = gcf ;
end ;
if (isempty(H))
H = gcf ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (nargin < 2)
lw = 0.5 ;
end ;
if (isempty(lw))
lw = 0.5 ;
end ;
lw = abs(lw) ;
if (~lw)
lw = 0.5 ;
end ;
%
% Fixing the look
% ~~~~~~~~~~~~~~~
% Axes:
set(H,'DefaultAxesFontName','Helvetica') ;
set(H,'DefaultAxesFontSize',14) ;
set(H,'DefaultAxesFontWeight','demi') ;
% or 'light', 'normal', 'bold'
set(H,'DefaultAxesFontAngle','normal') ;
% or 'italic', 'oblique'
set(H,'DefaultAxesLineWidth',1) ;

% Text over figure:


set(H,'DefaultTextFontName','Helvetica') ;
set(H,'DefaultTextFontSize',14) ;
set(H,'DefaultTextFontWeight','demi') ;
% or 'light', 'normal', 'bold'
set(H,'DefaultTextFontAngle','normal') ;
% or 'italic', 'oblique'
set(H,'DefaultTextRotation',0) ; % Horizontal writing.
%set(H,'DefaultTextRotation',90) ; % Vertical writing.
%set(H,'DefaultTextRotation',????) ; % Oblique writing [deg].
set(H,'DefaultTextHorizontalAlignment','center') ;
% or 'left', 'right'

% 2D graphic line:
set(H,'DefaultLineLineStyle','-') ; % or '-', ':', etc.
set(H,'DefaultLineLineWidth',lw) ;
set(H,'DefaultLineMarkerSize',8) ;

%&
4WVKPG/#6.#$FGW\IGPGTCN

% 3D graphic lines and surfaces:


set(H,'DefaultSurfaceLineStyle','none') ; % or '-', ':', etc.
set(H,'DefaultSurfaceLineWidth',lw) ;
set(H,'DefaultSurfaceMarkerSize',8) ;
set(H,'DefaultSurfaceFaceColor','interp') ;
set(H,'DefaultSurfaceFaceLighting','phong') ;
%
% END
%
% IS_VECT Test if input is a vector or at least a 2x2 matrix.
%
function v = is_vect(a)
%
% Input: a # MATLAB data
%
% Output: v # Test results:
% v = [n m], if a is a n-by-m matrix
% ([0,0] for empty matrix) ;
% v = -n, if a is a n-by-1 vector (column);
% . v = +m, if a is a 1-by-m vector (line)
% or a scalar.
%
% Explanation: This test is useful when reshaping of data to
% different sizes or orientations is necessary.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: May 4, 2001
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<IS_VECT>: ' ;
E1 = [FN 'Insufficient input arguments. Exit.'] ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Read and process the input


% ~~~~~~~~~~~~~~~~~~~~~~~~~~
if (nargin < 1)
war_err(E1) ;
return ;
end ;
[n,v] = size(a) ;
if (isempty(a) | ((n>1) & (v>1)))
v = [n,v] ;
elseif ((v==1) & (n>1))
v = -n ;
end ;
%
% END
%
% SCALING Helps to re-scale graphical variations.
%
function a = scaling(X,d)
%
% Inputs: X # Vector/Matrix recording the graphical
% variation(s) under concern
% d # Re-scaling factor (by default: 0.1).
%
% Output: a # 2-length vector recording the limits of vertical
% axis, after re-scaling
%
% Explanation: The routine returns the 2-length vector a that
% can be used to re-scale the graphical variation
% of X, such that the maximum/minimum values of
% axes are higher/lower by d*(max(X)-min(X))
% comparing to max(X)/min(X). By default, d=0.1
% (which means 10%). The argument d can be
% negative, allowing the user to perform zoom on a
% specified zone in the graphic. Usually, X is a
% vector. If X is a matrix, its columns are
% understood as different variations of the same
% parameter (like in case of MATLAB function PLOT)
% and max/min are computed accordingly.
%

%&
4WVKPG/#6.#$FGW\IGPGTCN

% Author: Dan Stefanoiu (*)


% Revised: Dan Stefanoiu (*)
% Last upgrade: April 14, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<SCALING>: ' ;
E1 = [FN ' Missing or empty input. Empty output. Exit.'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
a = [] ;
if (nargin < 2)
d = 0.1 ;
end ;
if (isempty(d))
d = 0.1 ;
end ;
d = d(1) ;
if (nargin < 1)
war_err(E1) ;
return ;
end ;
if (isempty(X))
war_err(E1) ;
return ;
end ;
%
% Scaling
% ~~~~~~~
a = min(min(X)) ;
X = max(max(X)) ;
d = d*(X-a) ;
a = [a-d X+d] ;
%
% END

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% SHOW_BTW Displays characteristics of Butterworth filters.


%
function show_btw(K,fc,M)
%
% Inputs: K # maximum order of filter (5, by default)
% fc # cut-off frequency:
% . when scalar in range (0,1),
% low-pass filter (0.5, by default)
% . when 2-length vector in range (0,1),
% band-pass filter
% M # resolution (1000, by default)
%
% Outputs: -------
%
% Explanation: The frequency characteristics (magnitude
% and phase) of low-pass and band-pass
% Butterworth filters are displayed.
% The order of filters varies in range 1:N.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: April 14, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin < 3)
M = 1000 ;
end ;
if (isempty(M))
M = 0.5 ;
end ;
M = abs(round(M(1))) ;
if (~M)
M = 1000 ;
end ;

%&
4WVKPG/#6.#$FGW\IGPGTCN

if (nargin < 2)
fc = 0.5 ;
end ;
if (isempty(fc))
fc = 0.5 ;
end ;
fc = vectoriz(fc) ;
fc(3:end) = [] ;
fc(fc>1) = 1./fc(fc>1) ;
fc(fc==0) = 0.5 ;
if (nargin < 1)
K = 5 ;
end ;
if (isempty(K))
K = 5 ;
end ;
N = abs(round(K(1))) ;
if (~K)
K = 5 ;
end ;
%
% Design of filters
% ~~~~~~~~~~~~~~~~~
F = [] ; % Magnitude.
phi = [] ; % Phase.
omega = pi*(0:(M-1))'/M ; % Normalized pulsation axis.
for k=1:K
[B,A] = butter(k,fc) ; % Design filter.
[A,B] = dbode(B,A,1,omega) ; % Extract magnitude and phase.
F = [F A] ; % Save magnitude.
phi = [phi B] ; % Save phase [deg].
end ;
phi = pi*phi/180 ; % Convert phase to [rad].
%
% Plotting frequency characteristics
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
figure, clf ;
fig_look(gcf,1.5) ;
subplot(211)

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

plot(omega,F) ;
grid ;
axis([0 pi -0.05 1.05]) ;
A = 'Frequency characteristics of ' ;
B = '-pass Butterworth filters. [K=1...' ;
if (length(fc)<2)
k = 'low' ;
else
k = 'band' ;
end ;
% set(gcf,'DefaultTextHorizontalAlignment','center') ;
title([A k B int2str(K) '].']) ;
ylabel('Magnitude') ;
subplot(212)
plot(omega,phi) ;
grid ;
k = axis ;
axis([0 pi k(3) k(4)+0.05*(k(4)-k(3))]) ;
xlabel('Normalized pulsation') ;
ylabel('Phase [rad]') ;
%
% END
%
% SHOW_TS Displays time series.
%
function show_ts(FIG,y,d,tit)
%
% Inputs: FIG # figure number
% (current figure number, by default)
% y # time series data (row vector)
% d # sampling instants
% (uniform sampling, by default)
% tit # figure title
% (‘A time series’, by default)
%
% Outputs: -------
%
% Explanation: Shows variation of a time series y sampled
% at instants given in d (or evenly spaced, when d

%&
4WVKPG/#6.#$FGW\IGPGTCN

% is missing or empty). Figure FIG is used in this


% aim. Within tit, if specified, the figure title
% is displayed.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
% Last upgrade: May 4, 2004
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<SHOW_TS>: ' ;
E1 = [FN 'Missing or empty time series. Exit.'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
if (nargin<1)
FIG = gcf ;
end ;
if (isempty(FIG))
FIG = gcf ;
end ;
if (nargin<2)
war_err(E1) ;
return ;
end ;
if (isempty(y))
war_err(E1) ;
return ;
end ;
y = vectoriz(y) ;
N = length(y) ;
if (nargin<3)
d = 1:N ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

if (isempty(d))
d = 1:N ;
end ;
d = vectoriz(d) ;
d = sort(d) ;
M = length(d) ;
if (M>N)
d = d(1:N) ;
elseif (M<N)
m = min(d(2:end)-d(1:(end-1))) ;
d = [d d(end)+m*(1:(N-M))] ;
end ;
if (nargin<4)
tit = 'A time series' ;
end ;
if (isempty(tit))
tit = 'A time series' ;
end ;
m = findstr(tit,'[') ;
if (~isempty(m))
M = findstr(tit,']') ;
if (isempty(M))
M = length(tit) ;
end ;
N = tit((m-1):M) ;
tit((m-1):M) = [] ;
else
N = [] ;
end ;
%
% Show time series
% ~~~~~~~~~~~~~~~~
figure(FIG),clf
fig_look(FIG,1.5) ;
plot(d,y,'-b') ;
m = scaling(y,0.05) ;
axis([d(1) d(end) m]) ;
grid ;
title(tit) ;

%&
4WVKPG/#6.#$FGW\IGPGTCN

xlabel('Momente de esantionare') ;
ylabel(['Amplitudine' N]) ;
%
% END
%
% VECTORIZ Reshapes a vector/matrix into a row vector.
%
function v = vectoriz(A)
%
% Input: A # Vector or matrix
%
% Output: v # Row vector
%
% Explanation: Reshapes the matrix or vector A into a
% row vector v. In case of matrices, the columns
% are transposed and successively enumerated
% on the row vector.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
%
% Last upgrade: March 24, 2003
%
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
% Messages
% ~~~~~~~~
FN = '<VECTORIZ>: ' ;
E1 = [FN 'Missing input. Empty output. Exit.'] ;
%
% Faults preventing
% ~~~~~~~~~~~~~~~~~
v = [] ;
if (nargin < 1)
war_err(E1) ;
return ;
end ;

%&
#URGEVGRTCEVKEGÉP/QFGNCTGCĩK+FGPVKHKECTGC5KUVGOGNQT

% Vectorizing
% ~~~~~~~~~~~
v = A ;
[m,n] = size(v) ;
if ((m>1) & (n>1))
v = reshape(v,1,m*n) ;
elseif (m>1)
v = v' ;
end ;
%
% END
%
% WAR_ERR Displays a message of warning or error.
%
function war_err(msg)
%
% Input: msg # Message to be displayed
% Outputs: -------
%
% Explanation: If the message msg is specified and non void,
% then it is displayed. Otherwise (if it is
% missing or void), a standard error message
% is displyed. In any case, unlike MATLAB function
% ERROR, the program that calls this routine
% is not automatically stopped unless
% an error occurred.
%
% Author: Dan Stefanoiu (*)
% Revised: Dan Stefanoiu (*)
%
% Last upgrade: April 13, 2004
%
% Copyright: (*) "Politehnica" University of Bucharest, ROMANIA
% Dept. of Automatic Control & Computer Science
%
% BEGIN
%
if ((nargin > 0) & (length(msg) > 0))
disp(' ') ;

%&
4WVKPG/#6.#$FGW\IGPGTCN

disp(msg) ;
disp(' ') ;
else
disp(' ') ;
disp('<WAR_ERR>: An error occurred.') ;
disp(' ') ;
end ;
%
% END
%

%&
Aspecte practice în Modelarea şi Identificarea Sistemelor

S
Seerriiii ddee ttiim
mpp ddiissppoonniibbiillee ppee C
CDD

Fişier Semnificaţie

ST01.M Rata lunară a numărului de şomeri din SUA între Ianuarie 1973 şi
iulie 1985 [%].
ST02.M Circulaţia monedei belgiene măsurată lunar, timp de 10 ani, între
1980 şi 1990 [miliarde BFr].
ST03.M Media lunară a numărului de pete solare observate între 1976 şi
1989.
ST04.M Distanţa lunară parcursa la U.K. Airlines pe cursele interne între
1982 şi 1989 [mii km].
ST05.M Rata lunară a şomajului în Marea Britanie între 1978 şi 1989 [%].

ST06.M Rata lunară a şomajului în Franţa între 1980 şi 1990 [%].

ST07.M Rata lunară a şomajului în Canada între 1979 şi 1989 [%].

ST08.M Veniturile lunare realizate din impozitele pe telefoane, într-o regiune


din SUA [milioane USD].
ST09.M Media lunară a timpului mediu de lucru săptămînal în SUA între 1979
şi 1989 [ore].
ST10.M Numărul lunar al bolnavilor operaţi de amigdalită la Spitalul 23
August din Bucureşti, între 1982 şi 1990.
ST11.M Intensitatea conştiinţei colective pe Terra măsurată lunar între 2000
şi 2004 la Kings College în Londra [mH].
ST12.M Intensitatea radio cosmică măsurată la radio-telescopul din
Indianapolis (SUA) între 2001 şi 2004 [mV DC].
ST13.M Rata de conversie între USD şi ROL începînd cu 15 octombrie 2001
(eşantionare neuniformă).
ST14.M Rata de conversie între EURO şi ROL începînd cu 10 ianuarie 2002
(eşantionare neuniformă).
ST15.M Rata de conversie între USD şi EURO începînd cu 10 ianuarie 2002
(eşantionare neuniformă).

CD-144

You might also like