%% Simulate Parameter Value from Prior and Posterior Distributions
% Consider the multiple linear regression model that predicts the US real gross national product (GNPR) by using a linear combination of industrial production index (IPI), total employment (E), and real wages (WR).
% \texttt{GNPR}_t=\beta_0+\beta_1\texttt{IPI}_t+\beta_2\texttt{E}_t+\beta_3\texttt{WR}_t+\varepsilon_t.
% For all t, \varepsilon_t is a series of independent Gaussian disturbances with a mean of 0 and variance \sigma^2.
% Assume these prior distributions:
% \beta\vert\sigma^2 \sim N_4\left({\rm M},\sigma^2 V\right). {\rm M} is a 4-by-1 vector of means, and V is a scaled 4-by-4 positive definite covariance matrix.
% \sigma^2 \sim IG(A,B). A and B are the shape and scale, respectively, of an inverse gamma distribution.
% These assumptions and the data likelihood imply a normal-inverse-gamma conjugate model.
% Load the Nelson-Plosser data set. Create variables for the response and predictor series.

load Data_NelsonPlosser
varNames = {'IPI' 'E' 'WR'};
X = DataTable{:,varNames};
y = DataTable{:,'GNPR'};

%
% Create a normal-inverse-gamma conjugate prior model for the linear regression parameters. Specify the number of predictors p and the variable names.

p = 3;
PriorMdl = bayeslm(p,'ModelType','conjugate','VarNames',varNames);

% PriorMdl is a conjugateblm Bayesian linear regression model object representing the prior distribution of the regression coefficients and disturbance variance.
%
% Simulate a set of regression coefficients and a value of the disturbance variance from the prior distribution.

rng(1); % For reproducibility
[betaSimPrior,sigma2SimPrior] = simulate(PriorMdl)

% betaSimPrior is the randomly drawn 4-by-1 vector of regression coefficients corresponding to the names in PriorMdl.VarNames. The sigma2SimPrior output is the randomly drawn scalar disturbance variance.
%
% Estimate the posterior distribution.

PosteriorMdl = estimate(PriorMdl,X,y);

% PosteriorMdl is a conjugateblm Bayesian linear regression model object representing the posterior distribution of the regression coefficients and disturbance variance.
%
% Simulate a set of regression coefficients and a value of the disturbance variance from the posterior distribution.

[betaSimPost,sigma2SimPost] = simulate(PosteriorMdl)

% betaSimPost and sigma2SimPost have the same dimensions as betaSimPrior and sigma2SimPrior, respectively, but are drawn from the posterior.
% Copyright 2012 The MathWorks, Inc.