Search code examples
matlabmultidimensional-arrayderivative

Is there a way to automatically get the gradient along the different dimensions of an array?


I am trying to find a way to automate the computation of the gradient of a function along its different dimensions, in Matlab.

I have found the gradient function here, but it requires me to write down individual output variables for each dimensions. Since I am calculating gradients in the middle of a sampling algorithm, I want the gradient calculation to automatically scale with higher dimensional input.

Basically, if F is a vector, I would want: G = gradient(F) to be a cell array with a single entry: a vector with all the gradient values. However, if F is 2D-array, I would like G to be a cell array with entries GX and GY, where GX is the gradient along the X direction and GY the gradient along the Y direction.


Solution

  • Something like this would do the trick:

    nd = sum(size(F)>1);
    G = cell(nd,1);
    [G{:}] = gradient(F);
    

    nd is the number of dimensions (simply calling ndims is not suitable, since a vector has 2 dimensions in MATLAB, everything has at least 2 dimensions). The [G{:}] construct assigns one output argument of gradient to each of the elements of the cell array.