%% Create Markov Chain from Observed State Transitions
% This example shows how to create a Markov chain object from a matrix containing observed transitions rather than a stochastic transition matrix.
% Consider a simple, two-state econometric model describing the state of the economy from 1857 through 2011. The states are recession and development. For more details, see US Business Cycle Expansions and Contractions.
% Load the recessions data set.

load Data_Recessions

% Recessions(j,1) contains the date (quarter as a serial number) that starts recession j, and Recessions(j,2) contains the corresponding end date.
%
% Convert the array of date serial numbers to a datetime array.

dtrec = datetime(Recessions,'ConvertFrom','datenum');

%
% Assume that the sample begins on 15Jun1857 and ends on 15Dec2011. Specify datetime variables for the start and end of the sampling period.

st = datetime(1857,6,15);  % Start of a recession
ed = datetime(2011,12,15); % Midst of development

%
% Count the number of transitions in the sampling period.

numTrans = calquarters(between(st,ed,'quarters'));

%
% During 1857 through 2011, count the number of transitions from a:
% State of development to a recession
% Recession to a state of development
% Recession to itself
% State of development to itself

dev2rec = size(dtrec,1) - 1; % Assume no knowledge about the state before st
rec2dev = size(dtrec,1);
rec2rec = sum(calquarters(between(dtrec(:,1),dtrec(:,2),'quarters')));
dev2dev = numTrans - dev2rec - rec2dev - rec2rec;

%
% Create a transition matrix containing the observed counts.

EmpP = [rec2rec rec2dev;
        dev2rec dev2dev];

%
% Create a Markov chain object characterized by the transition matrix. Specify state names associated with the rows and columns of EmpP.

mc = dtmc(EmpP,'StateNames',["Recession","Development"])

%
% MATLAB® normalizes the transition matrix so that all rows sum to 1. That is, MATLAB® computes a right-stochastic matrix from the matrix of observed transitions. Display the stochastic transition matrix of the Markov chain by using dot notation. Verify that every row of the transition matrix sums to 1.

mc.P
sum(mc.P,2)

%
% Plot a digraph of the Markov chain. Indicate probabilities of transition by using edge colors.

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

% The economy is more likely to persist in its current state than transition to another state.
% Copyright 2012 The MathWorks, Inc.