Ever try to compute the directional derivatives on a matrix? Google turn up menacing formulas for Taylor expansions, grid spacing, and boundary conditions?

A quick and simple way of computing derivatives is to perform arithmetic on shifted versions of the matrix, and vectorized indexing help Matlab speed things up. For example, use the following for the (central) x-derivative:

`dx = (M(:,[2:end end]) - M(:,[1 1:end-1]))/2`

You can even define inline functions to perform the shift and derivative operations. Below are definitions for the shift operations and first and second order derivatives.

`% shift operations`

shiftD = @(M) M([1 1:end-1],:);

shiftL = @(M) M(:,[2:end end]);

shiftR = @(M) M(:,[1 1:end-1]);

shiftU = @(M) M([2:end end],:);

`% derivatives`

Dx = @(M) (shiftL(M) - shiftR(M))/2;

Dy = @(M) (shiftU(M) - shiftD(M))/2;

Dxx = @(M) (shiftL(M) - 2*M + shiftR(M));

Dyy = @(M) (shiftU(M) - 2*M + shiftD(M));

Dxy = @(M) (shiftU(M) - shiftD(M) + shiftL(M) - shiftR(M))/4;

And use them like this:

`>> Ax = Dx(A)`

Ax =

-7.0000 -6.5000 5.5000 5.0000

3.0000 2.5000 -1.5000 -1.0000

-1.0000 -1.5000 2.5000 3.0000

5.0000 5.5000 -6.5000 -7.0000

`>> Ayy = Dyy(A)`

Ayy =

-11 9 7 -5

15 -13 -11 9

-9 11 13 -15

5 -7 -9 11

That is simply awesome. I didn’t think about using shifted matrices to compute directional derivatives. Definitely a computation time-saver, and will definitely exploit this in my next computer vision implementations. Thanks for sharing!