Gabriel
Gabriel

Reputation: 42329

Multi dimensional grid for general number of dimensions

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.

Upvotes: 1

Views: 270

Answers (1)

Divakar
Divakar

Reputation: 221504

We could use a list comprehension looping through the list of variables : x,y,z,q,etc. to create the slice notation and then simply feed it to mgrid -

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

With the slice constructor :

np.mgrid[[slice(A.min(),A.max(),10j) for A in L]]

Upvotes: 1

Related Questions