utility for numerical derivatives

git-svn-id: file:///home/sebastien/dynare/gsa_dyn@53 f1850c17-3b45-254b-b221-fcb05880fee1
time-shift
rattoma 2009-08-21 15:51:57 +00:00
parent 4ef416c41e
commit be0d4eb530
2 changed files with 71 additions and 0 deletions

32
GSA_distrib/fdjac.m Normal file
View File

@ -0,0 +1,32 @@
% FDJAC Computes two-sided finite difference Jacobian
% USAGE
% fjac = fdjac(f,x,P1,P2,...)
% INPUTS
% f : name of function of form fval = f(x)
% x : evaluation point
% P1,P2,... : additional arguments for f (optional)
% OUTPUT
% fjac : finite differnce Jacobian
%
% USER OPTIONS (SET WITH OPSET)
% tol : a factor used in setting the step size
% increase if f is inaccurately computed
% Copyright (c) 1997-2002, Paul L. Fackler & Mario J. Miranda
% paul_fackler@ncsu.edu, miranda.4@osu.edu
function fjac = fdjac(f,x,varargin)
tol = optget(mfilename,'tol',eps.^(1/3));
h = tol.*max(abs(x),1);
xh1=x+h; xh0=x-h;
h=xh1-xh0;
for j=1:length(x);
xx = x;
xx(j) = xh1(j); f1=feval(f,xx,varargin{:});
xx(j) = xh0(j); f0=feval(f,xx,varargin{:});
fjac(:,j) = (f1-f0)/h(j);
end
feval(f,x,varargin{:});

39
GSA_distrib/optget.m Normal file
View File

@ -0,0 +1,39 @@
% OPTGET Utility to get previously set function default values
% USAGE
% optvalue=optget(funcname,optname,optvalue);
% INPUTS
% funcname : name of function
% optname : name of option
% optval : option value
% OUTPUT
% optval : the current value of the option
%
% If the named field is not already defined, it will be set to
% optvalue, but optvalue has no effect if the field has already
% been set. Use OPTSET to change a previously set field.
%
% optget(funcname) returns the current values of the options structure.
% Copyright (c) 1997-2000, Paul L. Fackler & Mario J. Miranda
% paul_fackler@ncsu.edu, miranda.4@osu.edu
function optvalue = optget(funcname,optname,optvalue)
funcname = lower(funcname);
optvar=[funcname '_options'];
eval(['global ' optvar]) % declare a global variable
if nargin==1 % return the whole option structure
optvalue=(eval(optvar));
return
end
optname = lower(optname);
% if structure is empty or the named field does not exist
% set to the value passed
if isempty(eval(optvar)) | ~isfield(eval(optvar),optname)
eval([optvar '.' optname '=optvalue;']);
% otherwise return the value in the field
else
optvalue = eval([optvar '.' optname]);
end