MATLAB: Gradient function of matlab

gradientmathematicsmatrixpartial derivatives

Can someone please explain how gradient function works? (say, how is dx1(1,2)==0.5)
>> a=[1 3 2 11 18; 7 14 9 5 10; 15 7 13 18 9; 19 12 17 7 14 ]
a =
1 3 2 11 18
7 14 9 5 10
15 7 13 18 9
19 12 17 7 14
>> [dx1 dy1]=gradient(a)
dx1 =
2.0000 0.5000 4.0000 8.0000 7.0000
7.0000 1.0000 -4.5000 0.5000 5.0000
-8.0000 -1.0000 5.5000 -2.0000 -9.0000
-7.0000 -1.0000 -2.5000 -1.5000 7.0000
dy1 =
6.0000 11.0000 7.0000 -6.0000 -8.0000
7.0000 2.0000 5.5000 3.5000 -4.5000
6.0000 -1.0000 4.0000 1.0000 2.0000
4.0000 5.0000 4.0000 -11.0000 5.0000

Best Answer

The basic operation is to take half the difference between the two values on either side of the point you are considering. For example,
dx1(2,2) = 0.5 * (a(2,3) - a(2,1)) (i.e. 0.5*(9-7))
and
dx2(2,2) = 0.5 * (a(3,2) - a(1,2)) (i.e. 0.5*(7-3))
So for your example, dx1(1,2) = 0.5 * (2 - 1).
This has to be a little different for points on the edge of the matrix when a neighbouring value is not available. In these cases the single sided difference is taken, so for example
dx1(3,1) = a(3,2) - a(3,1) (i.e. 7-15)
If you are familiar with convolution, dx1 is just
conv2(a, [0.5 0 -0.5])
except for the left and right columns, and dy1 is
conv2(a, [0.5 0 -0.5].')
except for the top and bottom rows.