user832035
user832035

Reputation:

1D index to 3D coordinates

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

Upvotes: 6

Views: 6327

Answers (2)

Timorgizer
Timorgizer

Reputation: 69

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;
}

Upvotes: 3

Zong
Zong

Reputation: 6230

x = index / (size * size)
y = (index / size) % size
z = index % size

Upvotes: 11

Related Questions