%% Compute Filtered State Probabilities
% Compute filtered state probabilities from a two-state Markov-switching dynamic regression model for a 1-D response process. This example uses arbitrary parameter values for the data-generating process (DGP).
%
%% Create Fully Specified Model for DGP
% Create a two-state discrete-time Markov chain model for the switching mechanism.

P = [0.9 0.1; 0.2 0.8];
mc = dtmc(P);

% mc is a fully specified dtmc object.
% For each state, create an AR(0) (constant only) model for the response process. Store the models in a vector.

mdl1 = arima('Constant',2,'Variance',3);
mdl2 = arima('Constant',-2,'Variance',1);
mdl = [mdl1; mdl2];

% mdl1 and mdl2 are fully specified arima objects.
% Create a Markov-switching dynamic regression model from the switching mechanism mc and the vector of submodels mdl.

Mdl = msVAR(mc,mdl);

% Mdl is a fully specified msVAR object.
%
%% Simulate Data from DGP
% filter requires responses to compute filtered state probabilities. Generate one random response and state path, both  of length 30, from the DGP.

rng(1000); % For reproducibility
[y,~,sp] = simulate(Mdl,30);

%
%% Compute State Probabilities
% Compute filtered and smoothed state probabilities from the Markov-switching model given the simulated response data.

fs = filter(Mdl,y);
ss = smooth(Mdl,y);

% fs and ss are 30-by-2 matrices of filtered and smoothed state probabilities, respectively, for each period in the simulation horizon.  Although the filtered state probabilities at time t (fs(t,:)) are based on the response data through time t (y(1:t)), the smoothed state probabilities at time t (ss(t,:)) are based on all observations.
% Plot the simulated state path and the filtered and smoothed state probabilities on the same graph.

figure
plot(sp,'m')
hold on
plot(fs(:,2),'r')
plot(ss(:,2),'g')
yticks([0 1 2])
xlabel("Time")
title("Observed States with Estimated State Probabilities")
legend({'Simulated states','Filtered probability: state 2',...
    'Smoothed probability: state 2'})
hold off

% Copyright 2019 The MathWorks, Inc.