t = [ 0 : 0.02 : 4]';
%u = 0 .* t ;
u = 30 * cos(t);	% Enter desired input here

n = length(t);

% System

A  = [ 0 1 0; 0 0 1; -6 -11 -6 ];
B  = [ 0 ; 0 ; 1 ];
C  = [ 1 0 0 ];
D  = 0;
x0 = [ -1 ; 1 ; 1]

[y,     x]     = lsim(A,B,C,D,u,t,x0);

% Reduced Order Observer
A11 = A(1:1,1:1);
A12 = A(1:1,2:3);
A21 = A(2:3,1:1);
A22 = A(2:3,2:3);
B1  = B(1:1,1:1);
B2  = B(2:3,1:1);
H = [ -2 ; 17];
F = A22 - H * A12;
Dm=F * H + A21 - H * A11;
G = B2 - H * B1;
Co= [ 1 0 ];
Bo= [G, Dm];
Uo= [u, y];
Do= [0 0];

% simulation

[y_hat, eta] = lsim(F,Bo,Co,Do,Uo,t);
for i = 1:n
x_2hat(i,:) = eta(i,:) + H' * y(i);
end
plot(t,     x(:,1),'r-',t,       x(:,2),'g-', t,     x(:,3),'b-', ...
                        t,  x_2hat(:,1),'g--',t,x_2hat(:,2),'b--' )
xlabel('Time in seconds')
TITLE('Reduced Order Observer and System response: u=30cos(t)')
legend('x1','x2','x3');
