How to create a multidimensional array with numpy.mgrid

I wonder how to create a grid (multidimensional array) with numpy mgrid for an unknown number of dimensions (D), each dimension with a lower and upper border and the number of boxes:

n_bins = numpy.array([100 for d in numpy.arrange(D)]) bounds = numpy.array([(0.,1) for d in numpy.arrange(D)]) grid = numpy.mgrid[numpy.linspace[(numpy.linspace(bounds(d)[0], bounds(d)[1], n_bins[d] for d in numpy.arrange(D)] 

I think the above does not work, since mgrid creates an array of indexes, not values. But how to use it to create an array of values.

thanks

Aso.agile

+6
source share
1 answer

you can use

 np.mgrid[[slice(row[0], row[1], n*1j) for row, n in zip(bounds, n_bins)]] 

 import numpy as np D = 3 n_bins = 100*np.ones(D) bounds = np.repeat([(0,1)], D, axis = 0) result = np.mgrid[[slice(row[0], row[1], n*1j) for row, n in zip(bounds, n_bins)]] ans = np.mgrid[0:1:100j,0:1:100j,0:1:100j] assert np.allclose(result, ans) 

Note that np.ogrid can be used in many places where np.mgrid used and requires less memory because arrays are smaller.

+6
source

All Articles