arrays - 1D 索引的 4D 位置?

标签 arrays multidimensional-array 3d

我需要从 1D 数组中提取 4D 位置。我可以看到 2D 和 3D 的情况如何,但我很难理解第四维......

对于 2D:

int* array = new int[width * height];
int index = y * width + x;
int x = index / height
int y = index - x * height;

对于 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);

对于 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 = ??

最佳答案

索引公式由任何给定维度值与所有先前维度的乘积得出。

Index = xn ( D1 * ... * D{n-1} ) + x{n-1} ( D1 * ... * D{n-2} ) + ... + x2 * D1 + x1

对于 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... */

一般公式的形式为

xn = ( ( Index - Index( x1, ..., x{n-1} ) ) / Product( D1, ..., D{N-1} ) ) % Dn

关于arrays - 1D 索引的 4D 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142417/

相关文章:

java - 将数组转换为多维数组 - Java

java - 如何在单个数组中返回重复三次的数组?

javascript - 如何获取对象数组中对象所有属性值的数组?

javascript - 使用数据库中的数据和生成的 JavaScript 创建 JSON

javascript - 如何将以下对象数组解析为以下格式以进行显示

c - 如何使用 OpenGL 按特定顺序绘制贴花?

ios - JSON 到多维数组

c - 将二维数组传递给 C 函数

opengl - 使用 gluLookAt() 横向移动; C++

OpenCV 3D 垫到矢量