Index into vector field in 2 or 3 dimensions
<p>I have <code>vecfield</code> which is an <code>ndarray</code> with <code>m</code> entries for each spatial location in a (discrete) 2 or 3 dimensional space with shape <code>(w, h)</code> or <code>(w, h, d)</code>. Now I get an <code>ndarray</code> with a list of indices <code>(i, j)</code> or <code>(i, j, k)</code> and I'd like to read the <code>m</code> entries corresponding to each index.</p>

<p>Code (for 2D) is probably more helpful:</p>

<pre><code>vecfield = np.zeros([w, h, m]) 
fill_me_with_data(vecfield)
idx = generate_indices() 
# idx is now for example ndarray with [[0, 0], [9, 8], [15, 6], [9, 1]]
result = vecfield[idx, :]
# result should now be 4 x m (4 because 'idx' has 4 indices)
</code></pre>

<p>It seems that idx gets "linearized" and then used as index, so it does not work that way. <strong>How can I achieve what I want?</strong></p>

<p>You should have a read about the way numpy advanced indexing works <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a>. I think what you want is:</p>

<pre><code>vecfield[zip(idx)]
</code></pre>

<p><code>zip(idx)</code> returns the list of first components followed by the list of second components, which is what you need to pass for advanced indexing.</p>

python numpy