index to subscript, subscript to index

weblog/

Many dimensional grids always give me a headache when trying to convert indices to subscripts. Subscripts to indices is more or less straightforward. If you're dealing with a 3D array with lengths: nx,ny,nz corresponding to subscripts: i,j,k, then converting a subscript to an index is as simple as:
``````index = i + nx*(j+ny*k)
``````
The other way around is a little trickier, but has a simple derivation if you forget it. Start with the formula above:
``````i + nx*(j+ny*k) = index
``````
Now notice that `nx*(j+ny*k)` is of course divisible by `nx` so moding both sides by nx gives you:
``````i = index % nx
``````
Now you know index and i, so move those to the right hand side and begin again.
``````nx*(j+ny*k) = index - i
``````
Divide through by nx:
``````
j+ny*k = (index - i)/nx
``````
Now you can apply the same idea to j and ny. So moding both sides by ny gives you:
``````
j = (index - i)/nx % ny
``````
Finally you know everything but k so the last equation is:
``````
ny*k = (index - i)/nx - j
``````
Divide through by ny:
``````
k = ((index - i)/nx-j)/ny
``````
In summary to convert index to i,j,k of a 3d array of size nx by ny by nz:
``````i = index % nx
j = (index - i)/nx % ny
k = ((index - i)/nx-j)/ny
``````
The pattern here is pretty clear. And so it should be easy to generalize to whatever dimension array you are using 2D, 4D, N-dimensional. Note:This assumes you are using Column major ordering as in matlab (ind2sub, sub2ind). If you're using Row order just do every step in Spanish.