John Doe
John Doe

Reputation: 23

Generation of multidimensional Grid in Python

I have a N dimensional array of points that represents the sampling of a function. Then I am using the numpy histogramdd to create a multi dimensional histogram :

histoComp,edges = np.histogramdd(pointsFunction,bins =  [np.unique(pointsFunction[:,i]) for i in range(dim)])

Next I am trying to generate a "grid" with the coordinate of the different points of each bin. To do so, I am using :

Grid = np.vstack(np.meshgrid([edges[i] for i in range(len(edges))])).reshape(len(edges),-1).T

However this doesn't work the way I expected it to because the input of np.meshgrid is a list of arrays instead of arrays... But I have to use a generator given that the number of edges is not known.

Any tips ?

---UPDATE--- Here is an example of what I mean by "not working"

>>>a = [4, 8, 7, 5, 9]
>>>b = [7, 8, 9, 4, 5]

So this is the kind of result I want :

>>>np.vstack(np.meshgrid(a,b)).reshape(2,-1).T
array([[4, 7],
   [8, 7],
   [7, 7],
   [5, 7],
   [9, 7],
   [4, 8],
   [8, 8],
   [7, 8],
   [5, 8],
   [9, 8],
   [4, 9],
   [8, 9],
   [7, 9],
   [5, 9],
   [9, 9],
   [4, 4],
   [8, 4],
   [7, 4],
   [5, 4],
   [9, 4],
   [4, 5],
   [8, 5],
   [7, 5],
   [5, 5],
   [9, 5]])

But this is the result I get :

>>> np.vstack(np.meshgrid([a,b])).reshape(2,-1).T
array([[4, 7],
   [8, 8],
   [7, 9],
   [5, 4],
   [9, 5]])

Thank you,

Upvotes: 2

Views: 2370

Answers (1)

unutbu
unutbu

Reputation: 879103

Use the * argument unpacking operator:

np.meshgrid(*[A, B, C])

is equivalent to

np.meshgrid(A, B, C)

Since edges is a list, np.meshgrid(*edges) unpacks the items in edges and passes them as arguments to np.meshgrid.

For example,

import numpy as np

x = np.array([0, 0, 1])
y = np.array([0, 0, 1])
z = np.array([0, 0, 3])
xedges = np.linspace(0, 4, 3)
yedges = np.linspace(0, 4, 3)
zedges = np.linspace(0, 4, 3)
xyz = np.vstack((x, y, z)).T
hist, edges = np.histogramdd(xyz, (xedges, yedges, zedges))
grid = np.vstack(np.meshgrid(*edges)).reshape(len(edges), -1).T

yields

In [153]: grid
Out[153]: 
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  2.],
       [ 0.,  0.,  4.],
       ...
       [ 2.,  4.,  4.],
       [ 4.,  4.,  0.],
       [ 4.,  4.,  2.],
       [ 4.,  4.,  4.]])

Upvotes: 6

Related Questions