简体   繁体   中英

How to create a single array to represent a 3D grid of points in python

So what I'm trying to do is create a 3D grid in python that can be used to interpolate some data I will be given at each of the points on the grid. What I want is to be able to have one 3D array that I can use to pick any point on the grid. For example if I wanted to pick the point along the 3rd row of x, the 2nd row of y and the 1st row of z I would do points[0, 1, 2] .

I've started with this:

X, Y, Z = np.arange(-0.75, 0.751, 0.5), np.arange(-0.75, 0.751, 0.5), np.arange(-0.75, 0.751, 0.5)

Giving me what possible values of x,y and za point can have. The grid I will be required to make will have equally spaced points. I would preferably like to keep everything in numpy.

You can use np.meshgrid along with np.arange :

r = np.arange(-0.75, 0.751, 0.5)
X, Y, Z = np.meshgrid(r, r, r)

This will be fine for a small number of elements, but generally you may prefer to use np.linspace to minimize total roundoff error across the span:

r = np.linspace(-0.75, 0.75, 4)

You can achieve a similar result by coding the grid "manually" with np.indices :

scale = [0.5, 0.5, 0.5]
offset = [-0.75, -0.75, -0.75]
np.indices((4, 4, 4), dtype=float) * scale + offset

The order of the arrays will be different than with meshgrid . I generally prefer the output of indices because of this, and because the arrays are stacked rather than returned as a tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM