Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A 3-D grid of regularly spaced points

Tags:

python

numpy

I want to create a list containing the 3-D coords of a grid of regularly spaced points, each as a 3-element tuple. I'm looking for advice on the most efficient way to do this.

In C++ for instance, I simply loop over three nested loops, one for each coordinate. In Matlab, I would probably use the meshgrid function (which would do it in one command). I've read about meshgrid and mgrid in Python, and I've also read that using numpy's broadcasting rules is more efficient. It seems to me that using the zip function in combination with the numpy broadcast rules might be the most efficient way, but zip doesn't seem to be overloaded in numpy.

like image 264
Jack Avatar asked Dec 22 '22 04:12

Jack


2 Answers

Use ndindex:

import numpy as np
ind=np.ndindex(3,3,2)
for i in ind:
    print(i)

# (0, 0, 0)
# (0, 0, 1)
# (0, 1, 0)
# (0, 1, 1)
# (0, 2, 0)
# (0, 2, 1)
# (1, 0, 0)
# (1, 0, 1)
# (1, 1, 0)
# (1, 1, 1)
# (1, 2, 0)
# (1, 2, 1)
# (2, 0, 0)
# (2, 0, 1)
# (2, 1, 0)
# (2, 1, 1)
# (2, 2, 0)
# (2, 2, 1)
like image 77
unutbu Avatar answered Dec 24 '22 18:12

unutbu


Instead of meshgrid and mgrid, you can use ogrid, which is a "sparse" version of mgrid. That is, only the dimension along which the values change are filled in. The others are simply broadcast. This uses much less memory for large grids than the non-sparse alternatives.

For example:

>>> import numpy as np
>>> x, y = np.ogrid[-1:2, -2:3]
>>> x
array([[-1],
      [ 0],
      [ 1]])
>>> y
array([[-2, -1,  0,  1,  2]])
>>> x**2 + y**2
array([[5, 2, 1, 2, 5],
      [4, 1, 0, 1, 4],
      [5, 2, 1, 2, 5]])
like image 22
rephorm Avatar answered Dec 24 '22 16:12

rephorm