Python: Calculate the Gradient of a 3D grid

gradient, grid, numpy, python

Solution

The Numpy documentation indicates that `gradient` works for any dimensions:

`numpy.gradient(f, *varargs)`

Return the gradient of an N-dimensional array.

The gradient is computed using central differences in the interior and first differences at the boundaries. The returned gradient hence has the same shape as the input array.

Parameters :

`f: array_like.` An N-dimensional array containing samples of a scalar function.

`*varargs:` 0, 1, or N scalars specifying the sample distances in each direction, that is: dx, dy, dz, ... The default distance is 1.

Returns :

`g: ndarray.` N arrays of the same shape as f giving the derivative of f with respect to each dimension.

Seems like you should be able to extend your 2-dimensional code to 3D like you would expect.

Problem

I have a cube of particles which I've projected onto a 2D grid, Projecting the particles onto the grid by a clouds in cells and weighting them by a scalar. I would then like the gradient of the scalar at every grid point. In 2D I am doing this using `np.gradient` and I get two arrays with the gradient in the x and y directions: ``` gradx, grady = np.gradient(grid) ``` Does anyone have any idea how I can generalize this to 3 Dimensions? The Clouds in Cells in 3D is fine but I am then left with a grid with the shape (700, 700, 700). As far as I can see `np.gradient` can't deal with this? Thanks, Daniel

Original source