1function H = bfgsi1(H0,dg,dx,Verbose,Save_files)
2% H = bfgsi1(H0,dg,dx,Verbose,Save_files)
3% Update Inverse Hessian matrix
4%
5% Inputs:
6%   H0  [npar by npar]  initial inverse Hessian matrix
7%   dg  [npar by 1]     previous change in gradient
8%   dx  [npar by 1]     previous change in x;
9%   Verbose [scalar]    Indicator for silent mode
10%   Save_files [scalar] Indicator whether to save files
11%
12% 6/8/93 version that updates inverse Hessian instead of Hessian
13% itself.
14%
15% Original file downloaded from:
16% http://sims.princeton.edu/yftp/optimize/mfiles/bfgsi.m
17%
18% Copyright (C) 1993-2009 Christopher Sims
19% Copyright (C) 2009-2017 Dynare Team
20%
21% This file is part of Dynare.
22%
23% Dynare is free software: you can redistribute it and/or modify
24% it under the terms of the GNU General Public License as published by
25% the Free Software Foundation, either version 3 of the License, or
26% (at your option) any later version.
27%
28% Dynare is distributed in the hope that it will be useful,
29% but WITHOUT ANY WARRANTY; without even the implied warranty of
30% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31% GNU General Public License for more details.
32%
33% You should have received a copy of the GNU General Public License
34% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
35
36if size(dg,2)>1
37    dg=dg';
38end
39if size(dx,2)>1
40    dx=dx';
41end
42Hdg = H0*dg;
43dgdx = dg'*dx;
44if (abs(dgdx) >1e-12)
45    H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx;
46else
47    disp_verbose('bfgs update failed.',Verbose)
48    disp_verbose(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))],Verbose);
49    disp_verbose(['dg''*dx = ' num2str(dgdx)],Verbose)
50    disp_verbose(['|H*dg| = ' num2str(Hdg'*Hdg)],Verbose)
51    H=H0;
52end
53if Save_files
54    save('H.dat','H')
55end
56