-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindiff_grad.m
More file actions
58 lines (52 loc) · 1.52 KB
/
findiff_grad.m
File metadata and controls
58 lines (52 loc) · 1.52 KB
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
48
49
50
51
52
53
54
55
56
57
58
function [gradfx] = findiff_grad(f, x, h, type)
%
% function [gradf] = findiff_grad(f, x, h, type)
%
% Function that approximate the gradient of f in x (column vector) with the
% finite difference (forward/centered) method.
%
% INPUTS:
% f = function handle that describes a function R^n->R;
% x = n-dimensional column vector;
% h = the h used for the finite difference computation of gradf
% type = 'fw' or 'c' for choosing the forward/centered finite difference
% computation of the gradient.
%
% OUTPUTS:
% gradfx = column vector (same size of x) corresponding to the approximation
% of the gradient of f in x.
gradfx = zeros(size(x));
h = h * norm(x);
switch type
case 'fw'
% Without separability
% for i=1:length(x)
% xh = x;
% xh(i) = xh(i) + h;
% prova = (f(xh) - f(x))/ h;
% prova
% gradfx(i) = sum((f(xh) - f(x))/ h);
%
% end
% EXPLOIT SEPARABILITY
xh = x+h;
gradfx = ((f(xh)-f(x))/h);
case 'c'
% Without separability
% for i=1:length(x)
% xh_plus = x;
% xh_minus = x;
% xh_plus(i) = xh_plus(i) + h;
% xh_minus(i) = xh_minus(i) - h;
% gradfx(i) = (f(xh_plus) - f(xh_minus))/(2 * h);
% end
% EXPLOIT SEPARABILITY
xh_plus = x+h;
xh_minus = x-h;
gradfx = ((f(xh_plus)-f(xh_minus))/(2*h));
otherwise %
% exact derivatives
gradf = @(x) (x.^3 + x -1);
gradfx = gradf(x);
end
end