I need to extract a 4D position from a 1D array. I can see how it goes for 2D and 3D but I'm having a hard time wrapping my head around the 4th dimension..
For 2D:
int* array = new int[width * height];
int index = y * width + x;
int x = index / height
int y = index - x * height;
For 3D:
int* array = new int[width * height * depth];
int index = z * width * height + y * width + z;
int x = index / (height * depth);
int y = index - (x * height * depth) / depth;
int z = index - (x * height * depth) - (y * depth);
For 4D ?
int* array = new int[width * height * depth * duration];
int index = w * width * height * depth + z * width * height + y * width + w;
int x = index / (height * depth * duration);
int y = ??
The indexing formula is given by the multiplication of any given dimension value with the product of all the previous dimensions.
Index = xn ( D1 * ... * D{n-1} ) + x{n-1} ( D1 * ... * D{n-2} ) + ... + x2 * D1 + x1
So for 4D
index = x + y * D1 + z * D1 * D2 + t * D1 * D2 * D3;
x = Index % D1;
y = ( ( Index - x ) / D1 ) % D2;
z = ( ( Index - y * D1 - x ) / (D1 * D2) ) % D3;
t = ( ( Index - z * D2 * D1 - y * D1 - x ) / (D1 * D2 * D3) ) % D4;
/* Technically the last modulus is not required,
since that division SHOULD be bounded by D4 anyways... */
The general formula being of the form
xn = ( ( Index - Index( x1, ..., x{n-1} ) ) / Product( D1, ..., D{N-1} ) ) % Dn
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With