| 1 |
function [VarXAll, E_YVarXGivenY, Var_YEXGivenY] = fn_PosteriorVarianceDecomposition(xydraws,probs) |
| 2 |
%--- Inputs: |
| 3 |
% xydraws: a matrix with rows being x draws and columns being y draws (columns to be conditioned). |
| 4 |
% probs: a vector of probabilities for y draws (length(probs) must be the same as size(xydraws,2)) |
| 5 |
%--- Outputs: |
| 6 |
% VarXAll: Var(X) -- overall variance |
| 7 |
% E_YVarXGivenY: E_Y Var(X|Y) -- uncertainty of not knowing the correct true value of X for a given Y. |
| 8 |
% Var_YEXGivenY: Var_Y E(X|Y) -- varianation in the estimator of X due to uncertainty about the choice of Y. |
| 9 |
% |
| 10 |
% Mathematically and numerically, it must be that VarXAll = E_YVarXGivenY + Var_YEXGivenY. |
| 11 |
% |
| 12 |
% Written by T. Zha, October 2009 |
| 13 |
% |
| 14 |
% Copyright (C) 1997-2012 Tao Zha |
| 15 |
% |
| 16 |
% This free software: you can redistribute it and/or modify |
| 17 |
% it under the terms of the GNU General Public License as published by |
| 18 |
% the Free Software Foundation, either version 3 of the License, or |
| 19 |
% (at your option) any later version. |
| 20 |
% |
| 21 |
% It is distributed in the hope that it will be useful, |
| 22 |
% but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 23 |
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 24 |
% GNU General Public License for more details. |
| 25 |
% |
| 26 |
% If you did not received a copy of the GNU General Public License |
| 27 |
% with this software, see <http://www.gnu.org/licenses/>. |
| 28 |
% |
| 29 |
|
| 30 |
n_ydraws = size(xydraws,2); |
| 31 |
if (nargin==1), probs = (1/n_ydraws)*ones(n_ydraws,1); end |
| 32 |
|
| 33 |
|
| 34 |
%---------------- Overall variance -------------------- |
| 35 |
VarXAll1st = 0.0; |
| 36 |
VarXAll2nd = 0.0; |
| 37 |
xy1st = mean(mean(xydraws)); |
| 38 |
xy2nd = mean(mean(xydraws.^2)); |
| 39 |
for (yi=1:n_ydraws) |
| 40 |
xGiveny1st = mean(xydraws(:,yi)); |
| 41 |
xGiveny2nd = mean(xydraws(:,yi).^2); |
| 42 |
VarXAll1st = VarXAll1st + probs(yi) * xGiveny1st; |
| 43 |
VarXAll2nd = VarXAll2nd + probs(yi) * xGiveny2nd; |
| 44 |
end |
| 45 |
VarXAll = VarXAll2nd - VarXAll1st^2; |
| 46 |
|
| 47 |
|
| 48 |
%-------------- The component E_YVarXGivenY -------------------- |
| 49 |
E_YVarXGivenY = 0.0; |
| 50 |
for (yi=1:n_ydraws) |
| 51 |
VarXGivenY = mean(xydraws(:,yi).^2) - (mean(xydraws(:,yi)))^2; |
| 52 |
E_YVarXGivenY = E_YVarXGivenY + probs(yi) * VarXGivenY; |
| 53 |
end |
| 54 |
E_YVarXGivenY = E_YVarXGivenY; |
| 55 |
|
| 56 |
%-------------- The component Var_YEXGivenY -------------------- |
| 57 |
Var_YEXGivenY1st = 0.0; |
| 58 |
Var_YEXGivenY2nd = 0.0; |
| 59 |
for (yi=1:n_ydraws) |
| 60 |
EXGivenY = mean(xydraws(:,yi)); |
| 61 |
Var_YEXGivenY1st = Var_YEXGivenY1st + probs(yi) * EXGivenY; |
| 62 |
Var_YEXGivenY2nd = Var_YEXGivenY2nd + probs(yi) * EXGivenY^2; |
| 63 |
end |
| 64 |
Var_YEXGivenY = Var_YEXGivenY2nd - Var_YEXGivenY1st^2; |