Compute the gradient of a quantiy on a grid

1. Jul 8, 2011

matteo86bo

Hi, this might be a stupid question, but I was wondering how to computer the gradient of a quantity on a grid. I mean I have a grid made of cells (not necessarily of the same size) where the variable $\rho$ is defined at the center of every cell. How can I compute the gradient of this quantity?
It is wrong doing this:
$\nabla\rho(i)=\frac{\rho(i)}{\Delta(i)}$
where $\Delta(i)$ is the size of cell i.
I can't come up with other methods ...

2. Jul 8, 2011

HallsofIvy

I assume you are talking about a two-dimensional grid. The length of the gradient at each point is the fastest rate of increase over all directions and its direction is the direction in which you have that fastest increase. Assuming a rectangular grid so that each point has four immediate neighbors, each point has only four "neighbors" so you can only calculate four derivatives (difference between values at neighboring points divided by distance between those two points). Determine which of those is largest, take the value as the length of the gradient and its direction as the direction from the point to that neighbor (so there are only four possible directions.

You can extend that slightly by also using the "secondary" neighbors, lying on the "diagonal" of a grid square, giving 8 possible direction. You will have to take the longer diagonal distance into account.

3. Jul 12, 2011

matteo86bo

I didn't understand all you said ... I think I found the solution but I'm still a little bit concerned.

I need to computer a 3D gradient and for every direction I can use the "5-point finite difference approximation" of the gradient....

$$(\nabla\rho)_x=\frac{4}{3}\frac{\rho_{i+1}-\rho_{i-1}}{2\Delta x}-\frac{1}{3}\frac{\rho_{i+2}-\rho_{i-2}}{4\Delta x}$$

But how can I take into account the "diagonal" of the cube? The above formula compute the gradient only for one specific directorion ... I would like to know if there exists a formula to compute it by taking into account all the 27 neighbouring cells ...