Matrix Free Differentiation

Alternatively, see this post for an example of a fast dimension-agnostic matrix-free finite-difference stencil: Seemingly unnecessary allocation within for loop - #8 by stevengj

Note that, as mentioned in this post, you are typically better off using ghost cells / padding to implement your boundary conditions than putting if statements inside critical inner loops. And for something performance-critical like the difference operation, you really benefit from hard-coding/unrolling it.

See also some related discussions:

4 Likes