Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

arrays - 4D position from 1D index?

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 = ??
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...