%% Estimate Marginal Posterior Distribution
% Consider the linear regression model in Create Normal-Inverse-Gamma Semiconjugate Prior Model.
% Create a normal-inverse-gamma semiconjugate prior model for the linear regression parameters. Specify the number of predictors p and the names of the regression coefficients.

p = 3;
PriorMdl = bayeslm(p,'ModelType','semiconjugate','VarNames',["IPI" "E" "WR"]);

%
% Load the Nelson-Plosser data set. Create variables for the response and predictor series.

load Data_NelsonPlosser
X = DataTable{:,PriorMdl.VarNames(2:end)};
y = DataTable{:,'GNPR'};

%
% Estimate the marginal posterior distributions of \beta and \sigma^2.

rng(1); % For reproducibility
PosteriorMdl = estimate(PriorMdl,X,y);

% PosteriorMdl is an empiricalblm model object storing draws from the posterior distributions of \beta and \sigma^2 given the data. estimate displays a summary of the marginal posterior distributions to the command window. Rows of the summary correspond to regression coefficients and the disturbance variance, and columns to characteristics of the posterior distribution. The characteristics include:
% CI95, which contains the 95% Bayesian equitailed credible intervals for the parameters. For example, the posterior probability that the regression coefficient of WR is in [1.762, 3.178] is 0.95.
% Positive, which contains the posterior probability that the parameter is greater than 0. For example, the probability that the intercept is greater than 0 is 0.005.
% In this case, the marginal posterior is analytically intractable. Hence, estimate uses Gibbs sampling to draw from the posterior and estimate the posterior characteristics.
%
% By default, estimate draws and discards a burn-in sample of size 5,000. However, it is good practice to inspect a trace plot of the draws for adequate mixing and lack of transience. Plot a trace plot of the draws for each parameter. You can access the draws that compose the distribution, that is, the properties BetaDraws and Sigma2Draws, using dot notation.

figure;
for j = 1:(p + 1)
    subplot(2,2,j);
    plot(PosteriorMdl.BetaDraws(j,:));
    title(sprintf('%s',PosteriorMdl.VarNames{j}));
end

figure;
plot(PosteriorMdl.Sigma2Draws);
title('Sigma2');

% The trace plots indicate that the draws seem to be mixing well, that is, there is no detectable transience or serial correlation, and the draws do not jump between states.
% Copyright 2012 The MathWorks, Inc.