Indexing in numpy mgrid

I use numpy.mgridto create "arrays of coordinate indices"

y, x = np.mgrid[0:3, 0:2]
print x
array([[0, 1],
       [0, 1],
       [0, 1]])

In many situations, I take part of these arrays (for example, x[0, :]) and discard the rest of the data. Sometimes these slices are much smaller than the original arrays, which are expensive to compute (i.e. np.mgrid[0:512, 0:512, 0:512]). Does numpy have an equivalent [coord[view] for coord in np.mgrid[0:512, 0:512, 0:512]that doesn't generate large intermediate arrays?

I understand that the solution is trivial for a slice [0,:], but I'm looking for a general solution that handles any valid way to index numpy arrays

Edit

Some of them asked for specific examples for which they might look view. Ideally, I hope for a generic solution that handles any valid ndarray indexing method. Here are some specific examples for the 3x2 array above:

1) view = (1, slice(None, None, 2))

2) view = (np.array([0,1]), np.array([0, 1]))

3) view = np.array([[False, False], [False, True], [False, False]])

And I'm looking for a function like

def mgrid_with_view(array_shape, view)
    ...

This returns the equivalent [o[view] for o in np.indices(array_shape)]without unnecessary calculations or memory.

+5
source share
1 answer

As mentioned in HYRY, I believe that you want to avoid creating full arrays. mgridcreates a full array, however, if you use:

x, y = np.broadcast_arrays(*np.ogrid[0:2,0:3])

x y , np.arange(0,2) ( np.arange(0,3)), , . , , , , . (np.broadcast_arrays )

+1

All Articles