1function [mean,variance] = GetPosteriorMeanVariance(M,drop)
2
3% Copyright (C) 2012-2017 Dynare Team
4%
5% This file is part of Dynare.
6%
7% Dynare is free software: you can redistribute it and/or modify
8% it under the terms of the GNU General Public License as published by
9% the Free Software Foundation, either version 3 of the License, or
10% (at your option) any later version.
11%
12% Dynare is distributed in the hope that it will be useful,
13% but WITHOUT ANY WARRANTY; without even the implied warranty of
14% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15% GNU General Public License for more details.
16%
17% You should have received a copy of the GNU General Public License
18% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
19
20MetropolisFolder = CheckPath('metropolis',M.dname);
21FileName = M.fname;
22BaseName = [MetropolisFolder filesep FileName];
23load_last_mh_history_file(MetropolisFolder, FileName);
24NbrDraws = sum(record.MhDraws(:,1));
25NbrFiles = sum(record.MhDraws(:,2));
26NbrBlocks = record.Nblck;
27mean = 0;
28variance = 0;
29
30NbrKeptDraws = 0;
31for i=1:NbrBlocks
32    NbrDrawsCurrentBlock = 0;
33    for j=1:NbrFiles
34        o = load([BaseName '_mh' int2str(j) '_blck' int2str(i),'.mat']);
35        NbrDrawsCurrentFile = size(o.x2,1);
36        if NbrDrawsCurrentBlock + NbrDrawsCurrentFile <= drop*NbrDraws
37            NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
38            continue
39        elseif NbrDrawsCurrentBlock < drop*NbrDraws
40            FirstDraw = ceil(drop*NbrDraws - NbrDrawsCurrentBlock + 1);
41            x2 = o.x2(FirstDraw:end,:);
42        else
43            x2 = o.x2;
44        end
45        NbrKeptDrawsCurrentFile = size(x2,1);
46        %recursively compute mean and variance
47        mean = (NbrKeptDraws*mean + sum(x2)')/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
48        x2Demeaned = bsxfun(@minus,x2,mean');
49        variance = (NbrKeptDraws*variance + x2Demeaned'*x2Demeaned)/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
50        NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
51        NbrKeptDraws = NbrKeptDraws + NbrKeptDrawsCurrentFile;
52    end
53end
54