-
Notifications
You must be signed in to change notification settings - Fork 3
/
compute_numerical_gradient.m
47 lines (37 loc) · 1.02 KB
/
compute_numerical_gradient.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function numgrad = compute_numerical_gradient(J, theta)
% Computes numerical gradient of the given function J at point theta.
%
% In:
% J - a function that outputs a real-number.
% theta - a vector of parameters
% Calling y = J(theta) will return the function value at point theta.
%
% Out:
% numgrad - numerical gradient of J at point theta
%
% Written by: Mateusz Malinowski
% Email: [email protected]
% Created: 22.02.2012
%
EPSILON = 1e-7;
numOfEntries = length(theta);
denominator = 1.0 / (2.0 * EPSILON);
% % vectorized code - not really faster
% % standard basis multiplied by epsilon
% e = EPSILON * eye(numOfEntries);
%
% f =@(a, b) J(a + b) - J(a - b);
%
% numgrad = denominator * arrayfun(@(K) f(theta, e(:, K)), 1:numOfEntries)';
% unvectorized codes
% standard basis
e = zeros(numOfEntries, 1);
% here we store results
numgrad = zeros(numOfEntries, 1);
for k = 1:numOfEntries
e(k) = 1;
numgrad(k) = ...
denominator * ( J(theta + EPSILON * e) - J(theta - EPSILON * e) );
e(k) = 0;
end
end