%% defining LSSM
A=[ 0.6348 0.2593 0.4600
0.5413 0.4619 -2.1551
0.3717 -0.2875 -0.2284];
B=[-0.000373884261537862
-0.000282628577356680
6.75556005562987e-06];
C=[0.775419018631805 -0.351536834549575 -2.22055248727544
-1.06763937573713 1.60044239999917 2.15337710223348
-0.0104624868533414 -0.872193358462870 1.95243821622811
0.169459415037054 -2.05534089971536 3.53024245136833];
D=[0
0
0
0];
[A,B,C,D,~]=idssdata(LSSM);
[k n]=size(C); %dimension index
Qw=C'*C;
r_w=[1];
Rw=diag(r_w);
w=wgn(n,1,0);
v=wgn(k,1,0);
Q=w'*w; % ??
R=v'*v; % ??
% E|[ w [w.' v.']|=|Q N|
% | v] | |N.' R|
SYS=ss(A,B,C,D,1); %nargin 5 is discrete time step
%Design of Kalman estimator
[Kest,L,P,Mx,Z,My]=kalman(SYS,Q,R); % [A,C] observable
%calculating the LQ gain
[K,~]=lqr(SYS,Qw,Rw); % u = -Kx minimizes J(u) % [A,B] controllable
% SYS2=ss(Kest.A,Kest.B,Kest.C,Kest.D);
% [K,~]=lqr(SYS2,Qw,Rw);
% Form LQG regulator = LQ gain + Kalman filter.
F=lqgreg(Kest,K);
%Closed loop
cl_sys=feedback(SYS,F); % closed loop