Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create 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 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

like image 620
Aso Agile Avatar asked Nov 24 '12 14:11

Aso Agile


People also ask

What is Mgrid NumPy?

NumPy: mgrid() function The mgrid() function is used to get a dense multi-dimensional 'meshgrid'. An instance of numpy. lib. index_tricks. nd_grid which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape.

How do you create an array of all combinations of two NumPy arrays?

Numpy has a function to compute the combination of 2 or more Numpy arrays named as “numpy. meshgrid()“. This function is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing.


1 Answers

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.

like image 108
unutbu Avatar answered Oct 09 '22 18:10

unutbu