Search code examples
matrixindexingtraversal

Matrix linear indexing


I need to traverse a rectangular grid in continuous manner. Here is an example of what I want, the number means sequence:

   + x
   y 0  1  2
     5  4  3
     6  7  8

At each step I know the index in matrix. Is there any way to calculate the coordinates? The inverse mapping for [x + y * width] doesn't help, beacuse it creates "steps" or "jumps". Is there any solution?

Here is explanation for "steps" mentioned above:

  + x
   y 0  1  2
     3  4  5 //at this moment the X coordinate changes by 3, thus create step
     6  7  8

Solution

  • y = index / width
    if( y % 2 == 0 )
       x = index % width
    else
       x = width - index % width - 1
    

    I think that should do it. It's a single modification of the standard way of calculating with "steps" as you call them. You are only changing the way the calculation is done based upon the row.