%% State- and Cross-Variable Temporal Correlations
% Explicitly create the state-space model
% \begin{array}{*{20}{l}}
% {{x_{1,t}}} = 0.9x_{1,t-1} + 0.2u_{1,t}\\
% {{x_{2,t}}} = 0.1x_{1,t-1}-0.3x_{2,t-1} + u_{2,t}\\
% {{y_{1,t}}} = x_{1,t}  +\varepsilon_{1,t}\\
% {{y_{2,t}}} = x_{1,t} + x_{2,t} +\varepsilon_{2,t}.\\
% \end{array}}

A = [0.9 0; 0.1 -0.3];
B = [0.2 0; 0 1];
C = [1 0; 1 1];
D = eye(2);
Mdl = ssm(A,B,C,D,'StateType',[0 0]);

% Mdl is an ssm model object.
% Compute the temporal correlations of the measurement and state variables, as well as their cross-correlations.

[Cyy,Cxx,Cyx] = corr(Mdl);

% Each output variable is a 2-by-2-by-2 array containing temporal correlations from lag 0 to 1. Cyy contains the correlations between the measurement variables, Cxx contains the correlations among the state variables, and Cyx contains cross-correlations between the current observation of the measurement variables and lagged state variables.
% Plot a heatmap of the correlations between x_{1,t} and the lags of all state variables.

Cx1x = squeeze(Cxx(:,1,:));
hm = heatmap(Cx1x);
ylabel('h');
hm.YDisplayLabels = ["0" "1"];
xlabel('j')
hm.XDisplayLabels = ["1" "2"];
title('Corr(x_{1,t},x_{j,t - h})')

% Plot a heatmap of the cross-correlations between all measurement variables and the lags of x_{2,t}.

Cyx2 = Cyx(:,:,2);
hm = heatmap(Cyx2);
ylabel('h');
hm.YDisplayLabels = ["0" "1"];
xlabel('i')
hm.XDisplayLabels = ["1" "2"];
title('Corr(y_{i,t},x_{2,t - h})')

% Copyright 2021 The MathWorks, Inc.
%
%