  # Gradient - calculate it with Matlab

We are going to include the concepts in our Derivative function created before, to develop a Matlab function to calculate the gradient of a multidimensional scalar function. The function is going to have the following functionality:

% Usage: g = Grad(fun, x0)
%     fun: name of the multidimensional scalar function
%          (string). This
function takes a vector argument of
%          length n and returns a
scalar.
%     x0: point of interest (vector of length n)
%     g: column vector containing the gradient of fun at x0. The
%        size(g) = size(x)

% |delta(i)| is relative to |x0(i)|
delta = x0 / 1000;
for i = 1 : length(x0)
if x0(i) == 0
% avoids delta(i) = 0 (**arbitrary value**)
delta(i) = 1e-12;
end
% recovers original x0
u = x0;
u(i) = x0(i) + delta(i);
% fun(x0(i-1), x0(i)+delta(i), x0(i+1), ...)
f1 = feval ( fun, u );
u(i) = x0(i) - delta(i);
% fun(x0(i-1), x0(i)-delta(i), x0(i+1), ...)
f2 = feval ( fun, u );

% partial derivatives in column vector
g(i,1) = (f1 - f2) / (2 * delta(i));
end

We can try this algorithm, creating a function bowl (which includes two variables) in an separate m-file, as follows:

function y = bowl(x)
y = (x(1)-6)^2 + (x(2)-4.5)^4 / 25;

Then, we can test it from the command window:

x = [0 0]
f = 'bowl'
Expected: [-12 -14.58]'    Obtained: [-12.0011 -14.5803]'

x = [1 1]
Expected: [-10 -6.86]'    Obtained: [-10.0000 -6.8600]'

x = [6 4.5]
Expected: [0 0]'        Obtained: [0 0]'

x = [2 1.5]
Expected: [-8 -4.32]'    Obtained: [-8.0000 -4.3200]'

Now, another test with a different multivariable function:

function y = semirosen(x)
y = 100 * ( x(2) - x(1)^2 ) + ( 1 - x(1) )^2 ;

x = [0 0]
f = 'semirosen'
Expected: [-2 100]'      Obtained: [-2.0001 100.0000]'

x = [1 1]
Expected: [-200 100]'    Obtained: [-200.0000 100.0000]'

x = [9 15]
Expected: [-1784 100]'   Obtained: 1.0e+003 *[-1.7840    0.1000]'  