%************************In the name of Allah*****************************%
%***************************** IV *************************************%
clc
clear all
close all
%************************ initialization **********************************
num=[.5 1];
den=conv(conv([1 1],[2 3]),[.2 1]);
sys=tf(num,den);
Ts=.1;
sys_d=c2d(sys,Ts)
bode(sys_d)
grid on
hold on
N=100;
tt = [1:N]';
g1 = 1; g2 = 1; g3 = 1;
w1 = pi/3; w2 = pi/4; w3 = pi/5;
% % Please Uncomment each Input you want, and Comment the others.
u = ones(N,1);
%u = g1*sin(w1*tt);
u = g1*sin(w1*tt) + g2*sin(w2*tt) + g3*sin(w3*tt);
%u= wgn(N,1,2);
e= 9*wgn(N,1,-50);
y=zeros(N,1);
y(1)=e(1);
y(2)=2.372*y(1)+0.005233*u(1)+e(2);
y(3)=2.372*y(2)-1.85*y(1)+0.005233*u(2)+0.00007321*u(1)+e(3);
for k=4:N
y(k)=2.372*y(k-1)-1.85*y(k-2)+0.4724*y(k-3)+0.005233*u(k-1)+0.00007321*u(k-2)-0.003568*u(k-3)+e(k)+e(k-3);
end
%*************************THIS PART IS SPECIALLY ABOUT LS******************
% n : number of coefficients of denamenator of transfer function
% m : number of coefficients of numerator of transfer function
% N : number of samples
% a : column of matrix U
n=3;
m=n;
c=1;
for a=1 : n %This loop assigns first n columns of matrix U
j=1+a;
for k=j:N
U(k,a)=-y(c);
c=c+1;
end
c=1;
end
for a= n+1 : n+m % This loop assigns m columns of matrix U
c=1;
i=a-n;
for k=i+1:N
U(k,a)=u(c);
c=c+1;
end
end
%*************Now U is obtained . so we start to find teta*****************
teta_LS=((inv(U'*U))*U')*y;
den=[1 teta_LS(1) teta_LS(2) teta_LS(3)];
num=[0 teta_LS(4) teta_LS(5) teta_LS(6)];
h = tf (num , den , 0.1 , 'variable' , 'z^-1');
%***********************IV*************************
R=zeros(6,6);
H=zeros(6,1);
y=zeros(N,1);
y(2)=-teta_LS(1)*y(1)+teta_LS(4)*u(1);
y(3)=-teta_LS(1)*y(2)-teta_LS(2)*y(1)+teta_LS(4)*u(2)+teta_LS(5)*u(1);
for k=4:N
y(k)=-teta_LS(1)*y(k-1)-teta_LS(2)*y(k-2)-teta_LS(3)*y(k-3)+teta_LS(4)*u(k-1)+teta_LS(5)*u(k-2)+teta_LS(6)*u(k-3);
zeta=[-y(k-1) -y(k-2) -y(k-3) u(k-1) u(k-2) u(k-3)]';
phi=[-y(k-1) -y(k-2) -y(k-3) u(k-1) u(k-2) u(k-3)]';
R=R+zeta*phi';
H=H+zeta*y(k);
end
teta_iv=inv(R)*H
den=[1 teta_iv(1) teta_iv(2) teta_iv(3)];
num=[0 teta_iv(4) teta_iv(5) teta_iv(6)];
h = tf (num , den , 0.1 , 'variable' , 'z^-1')
bode(h)