I often find myself writing very similar code for one, two, and three dimensional versions of a given operation/algorithm. Maintaining all of these versions can become tedious. Simple code generation works fairly well, but it seems as thought there must be a better way.
Is there a relatively simple way to write an operation once and have it generalize to higher or lower dimensions?
One concrete example is: suppose I need to compute the gradient of a velocity field in spectral space. In three dimensions, the Fortran loops would look something like:
do k = 1, n do j = 1, n do i = 1, n phi(i,j,k) = ddx(i)*u(i,j,k) + ddx(j)*v(i,j,k) + ddx(k)*w(i,j,k) end do end do end do
ddx array is appropriately defined. (One could also do this with matrix multiplies.) The code for a two-dimensional flow is almost exactly the same, except: the third dimension is dropped from the loops, indexes, and number of components. Is there a better way of expressing this?
Another example is: suppose I have fluid velocities defined point-wise on a three dimensional grid. To interpolate the velocity to an arbitrary location (ie, not corresponding to grid points), one can use the one-dimensional Neville algorithm successively over all three dimensions (ie, dimensional reduction). Is there an easy way to do dimensional reduction given a one-dimensional implementation of a simple algorithm?