function Omega = InvWishartRndFcn(A,df)
% InvWishartRndFcn: Draws a positive definite matrix from an inverse Wishart distribution with
%                   parameter A and degrees of freedom df.
%
% USAGE:
%
%       Omega = InvWishartRndFcn(A,df)
%
% REQUIRED INPUT:  A (nxn) positive definite matrix with location parameters.
%
%                  df (integer) with degrees of freedom. It is required that df>=n
%
% REQUIRED OUTPUT: Omega (nxn) positive definite matrix.
%
%
%                       Written by: Anders Warne
%                                   New Area Wide Model Project
%                                   DG-R/EMO
%                                   European Central Bank (ECB)
%                                   Email: anders.warne@ecb.europa.eu
%                                   Copyright © 2006-2009 European Central Bank.
%
%                       First version: Januart 29, 2007.
%                        This version: January 22, 2009.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LICENSE INFORMATION:
%
%      YADA is free software: you can redistribute it and/or modify
%      it under the terms of the GNU General Public License as published by
%      the Free Software Foundation, either version 3 of the License, or
%      (at your option) any later version.
%
%      This program is distributed in the hope that it will be useful,
%      but WITHOUT ANY WARRANTY; without even the implied warranty of
%      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%      GNU General Public License for more details.
%
%      You should have received a copy of the GNU General Public License
%      along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%      YADA is released under the GNU General Public License, Version 3,
%      29 June 2007 <http://www.gnu.org/licenses/>. The current release of
%      the program was last modified by the ECB on the "This version" date
%      above.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CHANGELOG:
%
% * 13-11-2007: Updated the documentation.
%
% * 23-5-2008:  Updated the documentation.
%
% * 22-01-2009: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

n = size(A,1);
S = inv(A);
T = tril(randn(n),-1);
for i=1:n;
   T(i,i) = sqrt(rchi(df+1-i));
end;
L = chol(S)';
Omega = inv((L*T*(L*T)'));

%
% local function rchi
%

function chi = rchi(v)

if v<30;
   %
   % generate chi-square(v) draws by drawing normals
   % and adding up v such draws
   %
   t = randn(v,1);
   chi = t'*t;
else;
   %
   % use normal approximation since it is accurate enough but much faster
   %
   chi = 0.5*(randn+sqrt(2*v-1))^2;
end;

%
% end of InvWishartRndFcn.m
%
