%% Compute Expected Absorption Times
% Create an eight-state Markov chain from a randomly generated transition matrix with 50 infeasible transitions in random locations.  An infeasible transition is a transition whose probability of occurring is zero. Assign arbitrary names to the states.

numStates = 8;
Zeros = 50;
stateNames = strcat(repmat("Regime ",1,8),string(1:8));
rng(1617676169) % For reproducibility
mc = mcmix(8,'Zeros',Zeros,'StateNames',stateNames);

% Plot a digraph of the Markov chain mc. Specify node colors that identify transient and recurrent states and communicating classes.

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

% Find a recurrent class in the Markov chain mc by following this procedure:
% Classify the states by passing mc to classify. Return the array of class memberships ClassStates and the logical vector specifying whether the classes are recurrent ClassRecurrence.
% Extract the recurrent classes from the array of classes by indexing into the array using the logical vector.

[~,ClassStates,IsClassRecurrent] = classify(mc);
recurrent = ClassStates{IsClassRecurrent}

% Compute the expected hitting time for the states of the recurrent class, beginning from each state in the Markov chain.

ht = hittime(mc,recurrent);

% Extract and display the expected absorption times beginning from the transient states.

istransient = ~ismember(mc.StateNames,recurrent);
absorbtime = ht(istransient);
table(absorbtime,'RowNames',mc.StateNames(istransient))

% Copyright 2019 The MathWorks, Inc.