%% Return Default Distribution and Evaluations
% Consider the regression model in Plot Prior and Posterior Distributions.
% Load the Nelson-Plosser data set and create a default conjugate prior model.

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

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

%
% Plot the prior distributions. Request the values of the parameters used to create the plots and their respective densities.

[pointsUsedPrior,priorDensities1] = plot(PriorMdl);

% pointsUsedPrior is a 5-by-1 cell array of 1-by-1000 numeric vectors representing the values of the parameters that plot uses to plot the corresponding densities. The first element corresponds to the intercept, the next three elements correspond to the regression coefficients, and the last element corresponds to the disturbance variance.  priorDensities1 has the same dimensions as pointsUsed and contains the corresponding density values.
%
% Estimate the posterior distribution. Turn off the estimation display.

PosteriorMdl = estimate(PriorMdl,X,y,'Display',false);

%
% Plot the posterior distributions. Request the values of the parameters used to create the plots and their respective densities.

[pointsUsedPost,posteriorDensities1] = plot(PosteriorMdl);

% pointsUsedPost and posteriorDensities1 have the same dimensions as pointsUsedPrior.  The pointsUsedPost output can be different from pointsUsedPrior.  posteriorDensities1 contains the posterior density values.
%
% Plot the prior and posterior distributions. Request the values of the parameters used to create the plots and their respective densities.

[pointsUsedPP,posteriorDensities2,priorDensities2] = plot(PosteriorMdl,PriorMdl);

% All output values have the same dimensions as pointsUsedPrior. The posteriorDensities2 output contains the posterior density values. The priorDensities2  output contains the  prior density values.
%
% Confirm that pointsUsedPP is equal to pointsUsedPost.

compare = @(a,b)sum(a == b) == numel(a);
cellfun(compare,pointsUsedPost,pointsUsedPP)

% The points used are equivalent.
%
% Confirm that the posterior densities are the same, but that the prior densities are not.

cellfun(compare,posteriorDensities1,posteriorDensities2)
cellfun(compare,priorDensities1,priorDensities2)

% When plotting only the prior distribution, plot evaluates the prior densities at points that produce a clear plot of the prior distribution. When plotting both a prior and posterior distribution, plot prefers to plot the posterior clearly. Therefore, plot can determine a different set of points to use.
% Copyright 2012 The MathWorks, Inc.