%% Solve Continuous-Time Algebraic Riccati Equation
% To solve the algebraic Riccati equation A^T X+\textrm{XA}-\textrm{XB}B^T X+CC^T =0, consider the following matrices:
% A=
%   \left[ {\begin{array}{ccc}
%    1 & -2 & 3\\
%    -4 & 5 & 6 \\
%     7 & 8 & 9\\
%   \end{array} } \right]\;\;\;\;\;\;\;\;\;B=
%   \left[ {\begin{array}{c}
%    5\\
%    6\\
%     -7\\
%   \end{array} } \right]\;\;\;\;\;\;\;\;\;C=
%   \left[ {\begin{array}{ccc}
%    7 & -8 & 9\\
%   \end{array} } \right].
% The least effort approach is to use G=-BB^T and Q=C^T C, and then find the solution using icare.

A = [-1,2,3;4,5,-6;7,-8,9];
B = [5;6;-7];
C = [7,-8,9];
G = -B*B';
Q = C'*C;
[X1,K1,L1] = icare(A,[],Q,[],[],[],G)

% The above approach may lead to numerical inaccuracies when matrices B and C have large entries, since they are squared-up to compute the G and Q matrices. Due to limited numerical range, the computation may be less accurate or even fail. For example, if norm(B) is 1e6, then norm(G) is 1e12, and any eigenvalue within 1e-4 of the imaginary axis may be diagnosed as 'imaginary' due to numerical errors.
% For greater numerical accuracy, re-write the algebraic Riccati equation in the following way:
% A^T X+\textrm{XA}–\left\lbrack \textrm{XB},C^T \right\rbrack *\left\lbrack I,0;0,-I\right\rbrack \left\lbrack B^T X;C\right\rbrack =0.
% The above equation is the standard form of A^T X+\textrm{XA}-\left(\textrm{XB}+S\right)R^{-1} \left(B^T X+S^T \right)=0,
% where B=\left\lbrack B,0\right\rbrack ,\;S=\left\lbrack 0,C^T \right\rbrack ,\textrm{and}\;R=\left\lbrack I,0;0,-I\right\rbrack.
% Compute the solution using icare with the above values.

n = size(A,1);
m = size(B,2);
p = size(C,1);
R = blkdiag(eye(m),-eye(p));
BB = [B,zeros(n,p)];
S = [zeros(n,m),C'];
[X2,K2,L2,info] = icare(A,BB,0,R,S,[],[])

% Here, X2 is the unique stabilizing solution, K2 contains the state-feedback gain and L2 contains the closed-loop eigenvalues.
% Copyright 2018 The MathWorks, Inc.
%
%