Debian Codegraph @

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

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