% DADOS  DO SISTEMA
A = [0 1 0;0 0 1; 4 -6 4];
B = [0;0;1];
H = [0;0;1];
E = [2 0 0;0 1 0;0 0 0]; 
F = [0;0;1];
J = [0;0;0];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nx = size(A,1);
nw = size(H,2);
nu = size(B,2);
nz = size(E,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
opt = 2; % 1 - para norma H2
         % 2 - para norma Hoo

switch opt
    case 1
%%%%%%%%%%%%%%%%%%%%%%%% NORMA H2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 

% Descreve a LMI a ser projetada
setlmis([])

% declaracao de variveis
%===============
S = lmivar(1,[nx 1]);
Y = lmivar(2,[nu nx]);
W = lmivar(1,[nw 1]);
%===============

% descricao das LMIs
%===============
ct = 1;
lmiterm([ct,1,1,S],A,1,'s');
lmiterm([ct,1,1,Y],-B,1,'s');

lmiterm([ct,2,1,S],E,1);
lmiterm([ct,2,1,Y],-F,1);

lmiterm([ct,2,2,0],-1);

ct = ct+1;
lmiterm([-ct,1,1,W],1,1);
lmiterm([-ct,2,1,0],H);
lmiterm([-ct,2,2,S],1,1);

lmisys = getlmis;
%===============

% Declaracao funcao objetivo
options = [1e-4,2000,1e9,200,0];
%===============

np = decnbr(lmisys);

c = zeros(np,1);
for i=1:np
    Wi = defcx(lmisys,i,W);
    c(i) = trace(Wi);
end

[copt,xopt] = mincx(lmisys,c,options);

if (isempty(copt))
    Ss = [];
    Ys = [];
    Ws = [];
    return
end

Ss = dec2mat(lmisys,xopt,S);
Ys = dec2mat(lmisys,xopt,Y);
Ws = dec2mat(lmisys,xopt,W);
NormaH2 = trace(Ws) % Norma ao quadrado
K = Ys*inv(Ss)

    case 2
%%%%%%%%%%%%%%%%%%%%%%%% NORMA Hoo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% 
% Descreve a LMI a ser projetada
setlmis([])

% declaracao de variaveis
%===============
S = lmivar(1,[nx 1]);
rho = lmivar(1,[1 0]);
Y = lmivar(2,[nu nx]);
%===============

% descricao das LMIs
%===============
ct = 1;
lmiterm([ct,1,1,S],A,1,'s');
lmiterm([ct,1,1,Y],B,-1,'s');
lmiterm([ct,2,1,0],H');
lmiterm([ct,2,2,rho],-1,1);
lmiterm([ct,3,1,S],E,1);
lmiterm([ct,3,1,Y],F,-1);
lmiterm([ct,3,2,0],J);
lmiterm([ct,3,3,0],-1);

ct = ct+1;
lmiterm([-ct,1,1,S],1,1);

ct = ct+1
lmiterm([-ct,1,1,rho],1,1);

lmisys = getlmis;
%===============

% Declaracao funcao objetivo
options = [1e-4,2000,0,200,0];
%===============

np = decnbr(lmisys);

c = zeros(np,1);
c(decinfo(lmisys,rho)) = 1;

[copt,xopt] = mincx(lmisys,c,options);

if (isempty(copt))
    Ss = [];
    rhos = [];
    Ys = [];
return
end

Ss = dec2mat(lmisys,xopt,S);
rhos = dec2mat(lmisys,xopt,rho);
Ys = dec2mat(lmisys,xopt,Y);
NormaHoo = rhos % Norma ao quadrado
K = Ys*inv(Ss)
end
