1

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

Sebastian
  • 11
  • 1

1 Answers1

0

meshgrid as a function lets us use '*' unpacking:

In [412]: dmin,dmax=np.array([1,2,3]), np.array([5,6,7])
In [423]: arr = np.linspace(dmin,dmax,5)
In [424]: arr
Out[424]: 
array([[1., 2., 3.],
       [2., 3., 4.],
       [3., 4., 5.],
       [4., 5., 6.],
       [5., 6., 7.]])

I'm using sparse for a more compact display.

In [425]: atup = np.meshgrid(*arr.T,indexing='ij',sparse=True)
In [426]: atup
Out[426]: 
[array([[[1.]],
 
        [[2.]],
 
        [[3.]],
 
        [[4.]],
 
        [[5.]]]),
 array([[[2.],
         [3.],
         [4.],
         [5.],
         [6.]]]),
 array([[[3., 4., 5., 6., 7.]]])]

This ogrid does the same thing:

np.ogrid[1:5:5j,2:6:5j,3:7:5j]

Come to think of it, so is

np.ix_(arr[:,0],arr[:,1],arr[:,2])

though it doesn't have the nonsparse alternative.

hpaulj
  • 221,503
  • 14
  • 230
  • 353