%% Some examples using YALMIP to set up LMIs in CDS 210 HW

%% Example Problem
% How to find largest value of alpha such that, for given positive definite
% matrix Q and another matrix A, there exists P such that P >= 1e-6*I, 
% Q + (A'*P + P*A) <= -alpha*I, trace(P) = 1, and alpha >= 1e-6. 
% Here, inequality signs are in matrix positive definiteness sense, which boils 
% down to regular inequality sign for scalars. 

%% Problem data
A = [-1 0;0 -2];
Q = eye(2);

%% Define the variables alpha and P
% P is 2x2 symmetric matrix (by the definition of sign definiteness)
P = sdpvar(2);
%%
% alpha is scalar (i.e., 1x1 matrix)
alpha = sdpvar(1);
%%
% See help sdpvar for different uses of sdpvar (i.e., non-symmetric
% matrices etc.)

%% Impose the constraints
% Read help sdpvar/set
%%
% We will create a "problem" data structure and then put all the
% constraints into this structure.
prob = set(P >= 1e-6*eye(2));
%%
% Now, ADD another constraint TO the EXISTING problem.
prob = prob + set(Q+A'*P+P*A <= -alpha*eye(2));
%%
% And, other constraints
prob = prob + set(alpha >= 1e-6); 
prob = prob + set(trace(P) == 1);

%% Call the solver
% Specify the optimization objective. If there is no
% objective (i.e., if you are solving a feasibility problem, then you
% don't need to specify the objective - leave empty). 
%%
% Read help solvesdp for more options and help
%%
% YALMIP only minimizes the objective function. In order to maximize alpha
% subject to the previous constraints, our objective function is -alpha.
info = solvesdp(prob, -alpha);

%% Recover the optimal values. 

alpha = double(alpha)
P = double(P)

%% Hint for part (c)
% The output of solvesdp "info" has a field called problem which is equal
% to 0 if the problem is feasible and nonzero if there is any type of
% problems and/or infeasibilities in the problem. Monitoring this field in
% the line search in part (c) may be easiest. 




