MATLAB: Calculate the gradient of a function

gradient

Hello. I want to calculate the gradient of the function :
g={@(x)-x;@(x)x-1;@(y)-y;@(y)y-1};
with the following command :
gradient(g, [x, y]);
but I get the following error :
Undefined function or variable 'x'.
How I should proceed? Thanks.

Best Answer

You are confusing the numeric gradient function http://www.mathworks.com/help/matlab/ref/gradient.html with the symbolic gradient function, http://www.mathworks.com/help/symbolic/gradient.html
On the other hand, neither gradient() accepts a vector or cell array of function handles. Numeric gradient() accepts a numeric vector or array, and spacing distances for each of the dimensions. Symbolic gradient() accepts a scalar symbolic expression or symbolic function together with the variables to take the gradient over.
When you have a vector of functions to work with, you almost certainly want a jacobian rather than a gradient. Symbolic jacobian http://www.mathworks.com/help/symbolic/jacobian.html accepts a symbolic expression, symbolic function, or symbolic vector (but not a cell array of function handles.)
Related Question