%% Extract Unichain from Markov Chain
% Consider this theoretical, right-stochastic transition matrix of a stochastic process.
% P = \left[ {\begin{array}{*{20}{c}}
% 0.5&0.5&0&0\\
% 0&0.5&{0.5}&0\\
% 0&0&0.5&0.5\\
% 0&0&0.5&0.5
% \end{array}} \right].
% Create the Markov chain that is characterized by the transition matrix P. Name the states Regime 1 through Regime 4.

P = [0.5 0.5 0 0; 0 0.5 0.5 0; 0 0 0.5 0.5; 0 0 0.5 0.5];
mc = dtmc(P,'StateNames',["Regime 1" "Regime 2" "Regime 3" "Regime 4"]);

%
% Plot a digraph of the chain. Visually identify the communicating class to which each state belongs by using node colors.

figure;
graphplot(mc,'ColorNodes',true);

% Regimes 1 and 2 are in their own communicating class because Regime 2 does not transition to Regime 1.
%
% Extract the subchain containing Regime 2, a transient state. Display the transition matrix of the subchain.

sc = subchain(mc,"Regime 2");
sc.P

% Regime 1 is not in the subchain.
%
% Plot a digraph of the subchain.

figure;
graphplot(sc,'ColorNodes',true);

% The plot shows a unichain: a Markov chain containing one recurrent communicating class and the selected transient class.
% Copyright 2012 The MathWorks, Inc.