LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
num_grad.m
1% num_grad.m
2%
3% [df] = num_grad(func, X, h)
4%
5% Function to compute the numerical gradient of an arbitrary objective
6% function.
7%
8% Inputs:
9% -> func: Function handle for which numerical derivative is to
10% be obtained.
11% -> X: Sink of interest about which derivative is to be
12% obtained.
13% -> h: Tolerance for differentiation.
14%
15% Outputs:
16% -> df: Numerical derivative of function func (vector of size
17% n=length(X)).
18% -> NFV: Accumulator incremented by the number of function
19% evaluations which have taken place.
20%
21% Created by: Brendan C. Wood
22% Created on: February 14, 2011
23%
24% Copyright (c) 2011, Brendan C. Wood <b.wood@unb.ca>
25%
26
27function [df] = num_grad(func, X, h)
28
29df = zeros(length(X), 1);
30
31% for each dimension of objective function
32for i=1:length(X)
33 % vary variable i by a small amount (left and right)
34 x1 = X;
35 x2 = X;
36 x1(i) = X(i) - h;
37 x2(i) = X(i) + h;
38
39 % evaluate the objective function at the left and right points
40 [y1] = func(x1);
41 [y2] = func(x2);
42
43 % calculate the slope (rise/run) for dimension i
44 df(i) = (y2 - y1) / (2*h);
45end