7

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 bound and number of bins:

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 guess above doesn't work, since mgrid creates array of indices not values. But how to use it to create array of values.

Thanks

Aso.agile

1
  • numpy.arange ("array range"), not numpy.arrange Commented Oct 7, 2013 at 19:01

1 Answer 1

6

You might 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 is used, and it requires less memory because the arrays are smaller.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks @unutbu, it worked fine. Now how to convert this grid to D-dimensional points, i.e. 100**D x D shape?
reshape indeed gives 100D D-vectors, but surprisingly they are not unique, which also means not all possible vectors are there. What would be the way to get all D-points in the grid? I actually imagine it as a 100D table, and have no idea what to do with the additional dimension mgrid gives.
@LevLevitsky: To get points in the grid, take result.reshape(D, -1).T. The -1 will be replaced by whatever number is necessary to use all the values in the array. Thanks for the question, this is probably more like what AsoAgile was looking for.
@LevLevitsky: Suppose you have a function like def f(x): return x[0]**2+x[1]. Then grid = np.mgrid[0:5,0:5] is perfectly set up to evaluate f(grid), which computes f(x) for every point on the grid. Note that np.ogrid returns smaller arrays which would work here too, by taking advantage of broadcasting.
@LevLevitsky: It is true that you can not use this "trick" with any function. The computation must make sense in terms of numpy arrays. If your computation can not be expressed in terms of arrays, then you are stuck with using the much slower vectorize or frompyfunc functions.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.