6

i flattened a 3D array using the following code index = x*size*size + y * size + z

but can't figure out how to build the x,y,z indices from the index

i found another stackoverflow question with this but this doesn't work out for me, the indicis are always off

Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125

2 Answers2

11
x = index / (size * size)
y = (index / size) % size
z = index % size
Zong
  • 6,160
  • 5
  • 32
  • 46
3

Here are my functions to convert 3D coordinates to flattened coordinates back and forth.

I've tested them to certain extent, so they should do the job. The functions are in C++, but since they are mostly about math, the differences with any other language is minimal :)

inline CL_UINT getCellIndex(CL_UINT ix, CL_UINT iy, CL_UINT iz,
                            CL_UINT rx, CL_UINT ry, CL_UINT rz)
{
    return iz * rx * ry + iy * rx + ix;
}

inline CL_UINT3 getCellRefFromIndex(CL_UINT idx,CL_UINT rx, 
                                    CL_UINT ry,CL_UINT rz)
{
    CL_UINT3 result;
    CL_UINT a = (rx * ry);
    result.z = idx / a;
    CL_UINT b = idx - a * result.z;
    result.y = b / rx;
    result.x = b % rx;
    return result;
}
Timorgizer
  • 59
  • 2