1function [grad,err,finaldelta] = gradest(fun,x0)
2% gradest: estimate of the gradient vector of an analytical function of n variables
3% usage: [grad,err,finaldelta] = gradest(fun,x0)
5% Uses derivest to provide both derivative estimates
6% and error estimates. fun needs not be vectorized.
9% fun - analytical function to differentiate. fun must
10% be a function of the vector or array x0.
12% x0 - vector location at which to differentiate fun
13% If x0
is an nxm array, then fun
is assumed to be
14% a function of n*m variables.
17% grad - vector of first partial derivatives of fun.
18% grad will be a row vector of length numel(x0).
20% err - vector of error estimates corresponding to
21% each partial derivative in grad.
23% finaldelta - vector of final step sizes chosen for
24% each partial derivative.
28% [grad,err] = gradest(@(x) sum(x.^2),[1 2 3])
32% 5.8899e-15 1.178e-14 0
36% At [x,y] = [1,1], compute the numerical gradient
37% of the function sin(x-y) + y*exp(x)
39% z = @(xy) sin(diff(xy)) + xy(2)*exp(xy(1))
41% [grad,err ] = gradest(z,[1 1])
49% At the global minimizer (1,1) of the Rosenbrock function,
50% compute the gradient. It should be essentially zero.
52% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;
53% [g,err] = gradest(rosen,[1 1])
60% See also: derivest, gradient
63% Author: John D
'Errico
64% e-mail: woodchips@rochester.rr.com
66% Release date: 2/9/2007
68% get the size of x0 so we can reshape
72% total number of derivatives we will need to take
79 [grad(ind),err(ind),finaldelta(ind)] = derivest( ...
80 @(xi) fun(swapelement(x0,ind,xi)), ...
81 x0(ind),'deriv
',1,'vectorized
','no
', ...
85end % mainline function end
87% =======================================
89% =======================================
90function vec = swapelement(vec,ind,val)
91% swaps val as element ind, into the vector vec