# Multi dimensional grid for general number of dimensions

4157 views
3

I need to generate a grid for an array with a general/variable number of dimensions. In the 2D case, I know I can use mgrid:

``````# Some 2D data
N = 1000
x = np.random.uniform(0., 1., N)
y = np.random.uniform(10., 100., N)
xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()

# Obtain 2D grid
xy_grid = np.mgrid[xmin:xmax:10j, ymin:ymax:10j]
``````

How can I scale this approach when the number of dimensions is variable? Ie: my data could be `(x, y)` or `(x, y, z)` or `(x, y, z, q)`, etc.

The naive approach of:

``````# Md_data.shape = (M, N), for M dimensions
dmin, dmax = np.amin(Md_data, axis=1), np.amax(Md_data, axis=1)
Md_grid = np.mgrid[dmin:dmax:10j]
``````

does not work.

4

We could use a list comprehension looping through the number of variables to create the slice notation and then simply feed it to `mgrid` -

``````L = [x,y,z,q]
out = np.mgrid[[np.s_[A.min():A.max():10j] for A in L]]
``````

posted this