%% Simulate Multiple Paths
% Consider the following logistic TAR (LSTAR) model for the annual, CPI-based, Canadian inflation rate series y_t.
% State 1: y_t =-5+\varepsilon_{1,t}, where \varepsilon_{1,t} \sim N\left(0,0\ldotp 1^2 \right)\ldotp
% State 2: y_t =\varepsilon_{2,t}, where \varepsilon_{2,t} \sim N\left(0,0\ldotp 2^2 \right)\ldotp
% State 3: y_t =5+\varepsilon_{3,t}, where \varepsilon_{3,t} \sim N\left(0,0\ldotp 3^2 \right)\ldotp
% The system is in state 1 when y_t <2, the system is in state 2 when 2\le y_t <8, and the system is in state 3 otherwise.
% The transition function rate between states 1 and 2 is 3.5, and the transition function rate between states 2 and 3 is 1.5.
% Create an LSTAR model representing y_t.

t = [2 8];
tt = threshold([2 8],Type="logistic",Rates=[3.5 1.5]);
  
mdl1 = arima(Constant=-5,Variance=0.1);
mdl2 = arima(Constant=0,Variance=0.2);
mdl3 = arima(Constant=5,Variance=0.3);
  
Mdl = tsVAR(tt,[mdl1; mdl2; mdl3]);

% Load the Canadian inflation and interest rate data set.

load Data_Canada

% Extract the CPI-based inflation rate series.

INF_C = DataTable.INF_C; 
numObs = length(INF_C);

% Simulate ten paths from the model.  Specify the threshold variable type and its data.

Y = simulate(Mdl,numObs,NumPaths=10,Type="exogenous",Z=INF_C);

% Y is a numObs-by-10 matrix of simulated paths.  Each column represents an independently simulated path.
% In a tiled layout, plot the threshold transitions with the data by using ttplot,and plot the simulated paths to one tile.

tiledlayout(2,1)
nexttile
ttplot(tt,Data=INF_C)
colorbar('off')
xticklabels(dates(xticks))
nexttile
plot(dates,Y)
grid on
axis tight
title("Simulations")

% Y switches between submodels according to the value of the threshold variable INF_C.  Mixing is evident for observations near thresholds, such as at the inflation rates of 1964 and 1978.
% Copyright 2021 The MathWorks, Inc.