Debian Codegraph @

contrib/ms-sbvar/TZcode/MatlabFiles/hesscd.m

raw
1 function grdd = hesscd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,...
2 P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20)
3 % computing numerical hessian using a central difference with
4 % function grdd = hesscd(fcn,x0,grdh,Passed variables1)
5 %
6 % fcn: a string naming the objective function.
7 % x0: a column vector n*1, at which point the hessian is evaluated.
8 % grdh: step size.
9 % grdd: hessian matrix (second derivative), n*n.
10 %
11 % Copyright (C) 1997-2012 Tao Zha
12 %
13 % This free software: you can redistribute it and/or modify
14 % it under the terms of the GNU General Public License as published by
15 % the Free Software Foundation, either version 3 of the License, or
16 % (at your option) any later version.
17 %
18 % It is distributed in the hope that it will be useful,
19 % but WITHOUT ANY WARRANTY; without even the implied warranty of
20 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 % GNU General Public License for more details.
22 %
23 % If you did not received a copy of the GNU General Public License
24 % with this software, see <http://www.gnu.org/licenses/>.
25 %
26
27 stps = eps^(1/3);
28 % eps: floating point relative accuracy or machine precision: 2.22e-16
29 % stps: step size recommended by Dennis and Schnabel: 6.006e-6
30
31 x0 = x0(:);
32 tailstr = ')';
33 for i=nargin-3:-1:1
34 tailstr=[ ',P' num2str(i) tailstr];
35 end
36 f0 = eval([fcn '(x0' tailstr]);
37
38 % ** initializations
39 k = length(x0);
40 grdd = zeros(k);
41
42 % ** Computation of stepsize (dh)
43 if all(grdh)
44 dh = grdh;
45 else
46 ax0 = abs(x0);
47 if all(x0)
48 dax0 = x0 ./ ax0;
49 else
50 dax0 = 1;
51 end
52 dh = stps * (max([ax0 (1e-2)*ones(k,1)]'))' .* dax0;
53 end
54
55 xdh = x0 + dh;
56 dh = xdh - x0; % This increases precision slightly
57 dhm = dh(:,ones(k,1));
58 ee = eye(k) .* dhm;
59
60 i = 1;
61 while i <= k
62 j = i;
63 while j <= k
64
65 fune1 = eval([fcn '(x0 + ee(:,i) + ee(:,j)' tailstr]);
66 fune2 = eval([fcn '(x0 - ee(:,i) + ee(:,j)' tailstr]);
67 fune3 = eval([fcn '(x0 + ee(:,i) - ee(:,j)' tailstr]);
68 fune4 = eval([fcn '(x0 - ee(:,i) - ee(:,j)' tailstr]);
69 grdd(i,j) = (fune1 - fune2 - fune3 + fune4) / (4 * dh(i) * dh(j));
70
71 if i ~= j
72 grdd(j,i) = grdd(i,j);
73 end
74
75 j = j+1;
76 end
77 i = i+1;
78 end
79