Converting a one-dimensional flattened index into an N-dimensional vector index of an N-dimensional array

I have an N-dimensional array with the same number of elements (ie the same "length") in each dimension.

Given the one-dimensional index in the array, I want a function that returns the coordinates associated with this index. The way the array is indexed does not really matter (in the sense that all dimensions of the array are equal, and not one of them has priority in terms of the algorithms that will work in the array).

So, for example, if I have a 4x4x4 array, index 63 should return [3,3,3], index 0 should return [0,0,0], and index 5 should return [1,1,0],

I wrote the following function, where nDim is the number of dimensions and nBin is the length of each dimension:

def indicesOf(x,nDim,nBin) :
    indices = []
    for i in arange(0,nDim) :   
        index = (x/nBin**(i))%nBin
        indices.append(index)
        x -= index*nBin**i
    return indices

, - ? , "" , , . , - , !

python, C ( CUDA), pythons .

Jackolantern Eric . , , .

def indicesPowOf2(x,nDim,nBin) :
    logWidth = math.log(nBin,2)         
    indices = [0]*nDim
    for i in arange(nDim) :
        indices[i] = x & (nBin-1)
        x = x >> int(logWidth)
    return indices
+4
1

** ( ), , CUDA.

void indices(int x, int nDim, int nBin, int indices[]) {
    for(int i=0;i<nDim;i++) {
        indices[i] = x % nBin;
        x /= nBin;
    }
}

nBin 2, >> & / %.

+2

All Articles