Reputation: 571
I am using a 1D vector to represent a 3D data structure, with indices 0 to x*y*z, where x, y and z are the number of cells in each direction.
In order to index a specific cell [xi][yi][zi], I use:
index = xi + x*yi + x*y*zi ;
My problem is, I can't work out how to go the other way!
e.g. I want to get the individual coordinates represented in index 43.
I think I've worked out how to get xi:
xi = index % x ;
but I can't for the life of me get the others... :/
EDIT: Hmmm. Is this right?
xi = index % x;
yi = ((index - xi)/x) % y;
zi = ((index - xi - x*yi) / x) / y ;
Upvotes: 2
Views: 2050
Reputation: 1158
Try this:
xi = index % x;
yi = (index / x) % y;
zi = ((index / x) / y) % z;
This can be easily generalized as one might expect.
Upvotes: 4
Reputation: 10780
Some modular arithmetic should do the trick.
index % x = (xi + x*yi + x*y*zi) % x = xi % x,
but 0 <= xi < x therefore xi % x = xi.
Then for yi:
(index / x) % y = yi.
Then lastly:
index / (x * y) = zi.
EDIT:
In code (as opposed to math above) it would be:
xi = index % x;
yi = (index / x) % y;
zi = index / (x * y);
Upvotes: 1