Debian Codegraph @

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

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