LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
gradest.m
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)
4%
5% Uses derivest to provide both derivative estimates
6% and error estimates. fun needs not be vectorized.
7%
8% arguments: (input)
9% fun - analytical function to differentiate. fun must
10% be a function of the vector or array x0.
11%
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.
15%
16% arguments: (output)
17% grad - vector of first partial derivatives of fun.
18% grad will be a row vector of length numel(x0).
19%
20% err - vector of error estimates corresponding to
21% each partial derivative in grad.
22%
23% finaldelta - vector of final step sizes chosen for
24% each partial derivative.
25%
26%
27% Example:
28% [grad,err] = gradest(@(x) sum(x.^2),[1 2 3])
29% grad =
30% 2 4 6
31% err =
32% 5.8899e-15 1.178e-14 0
33%
34%
35% Example:
36% At [x,y] = [1,1], compute the numerical gradient
37% of the function sin(x-y) + y*exp(x)
38%
39% z = @(xy) sin(diff(xy)) + xy(2)*exp(xy(1))
40%
41% [grad,err ] = gradest(z,[1 1])
42% grad =
43% 1.7183 3.7183
44% err =
45% 7.537e-14 1.1846e-13
46%
47%
48% Example:
49% At the global minimizer (1,1) of the Rosenbrock function,
50% compute the gradient. It should be essentially zero.
51%
52% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;
53% [g,err] = gradest(rosen,[1 1])
54% g =
55% 1.0843e-20 0
56% err =
57% 1.9075e-18 0
58%
59%
60% See also: derivest, gradient
61%
62%
63% Author: John D'Errico
64% e-mail: woodchips@rochester.rr.com
65% Release: 1.0
66% Release date: 2/9/2007
67
68% get the size of x0 so we can reshape
69% later.
70sx = size(x0);
71
72% total number of derivatives we will need to take
73nx = numel(x0);
74
75grad = zeros(1,nx);
76err = grad;
77finaldelta = grad;
78for ind = 1:nx
79 [grad(ind),err(ind),finaldelta(ind)] = derivest( ...
80 @(xi) fun(swapelement(x0,ind,xi)), ...
81 x0(ind),'deriv',1,'vectorized','no', ...
82 'methodorder',2);
83end
84
85end % mainline function end
86
87% =======================================
88% sub-functions
89% =======================================
90function vec = swapelement(vec,ind,val)
91% swaps val as element ind, into the vector vec
92vec(ind) = val;
93
94end % sub-function end
95
96