Note that there are some explanatory texts on larger screens.

plurals
  1. POTransforming a one-dimensional, "flattened" index into the N-dimensional vector index of an N-dimensional array
    primarykey
    data
    text
    <p>I have an N-dimensional array, with the same number of items (i.e. the same "length") in each dimension.</p> <p>Given a one-dimensional index into the array, I want a function that returns the coordinates associated with that index. The way that the array is indexed actually doesn't matter (in the sense that all of the dimensions of the array are equal, with none having precedence in terms of algorithms that will be operating on the array).</p> <p>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]. </p> <p>I have written the following function, where nDim is the number of dimensions, and nBin is the length of each dimension:</p> <pre><code>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 </code></pre> <p>It seems to work -- but is there a more efficient way to make this calculation? To be honest, I have half "asked" this question just to share this solution, as I couldn't find a solution online. But if there is a more efficient way to do this, then great -- please share!</p> <p>The function above is written in python, but I have just been using this to prototype a C (actually CUDA) function, so none of pythons wonderful libraries are available to me.</p> <p>Here is a solution from combining JackOLantern and Eric's comments about the power of two sizes below. It seems to work for the handful of test cases I tried.</p> <pre><code>def indicesPowOf2(x,nDim,nBin) : logWidth = math.log(nBin,2) indices = [0]*nDim for i in arange(nDim) : indices[i] = x &amp; (nBin-1) x = x &gt;&gt; int(logWidth) return indices </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload