%% Compute Gradient at Specified Point
% Find the value of the gradient of a multivariate function at a specified point.
% Consider the multivariate function f(x,y) = x^2y^3.

x = -3:0.2:3;
y = x';
f = x.^2 .* y.^3;
surf(x,y,f)
xlabel('x')
ylabel('y')
zlabel('z')

%
% Calculate the gradient on the grid.

[fx,fy] = gradient(f,0.2);

%
% Extract the value of the gradient at the point (1,-2). To do this, first obtain the indices of the point you want to work with. Then, use the indices to extract the corresponding gradient values from fx and fy.

x0 = 1;
y0 = -2;
t = (x == x0) & (y == y0);
indt = find(t);
f_grad = [fx(indt) fy(indt)]

% The exact value of the gradient of f(x,y) = x^2y^3 at the point (1,-2) is
% \begin{array}{cl} \left( \nabla f \right)_{(1,-2)} &= 2xy^3 \hat{i} +
% 3x^2y^2 \hat{j}\\ &= -16 \hat{i} + 12 \hat{j}.\end{array}
% Copyright 2012 The MathWorks, Inc.