[英]How to generate an n-dimensional grid in python
I want to generate an n-dimensional grid. 我想生成一个n维网格。
For a 3D grid, I have the following working code (which creates a grid of 5X5X5 between (-1,1 ) 对于3D网格,我有以下工作代码(在(-1,1)之间创建一个5X5X5的网格)
import numpy as np
subdivision = 5
step = 1.0/subdivision
grid= np.mgrid[ step-1 : 1.0-step: complex(0, subdivision),
step-1 : 1.0-step: complex(0, subdivision),
step-1 : 1.0-step: complex(0, subdivision)]
I want to generalize this to n dimensions so something like 我想把它推广到n维,就像这样
grid = np.mgrid[step-1 : 1.0-step: complex(0,subdivision) for i in range(n)]
But this obviously doesnt work. 但这显然不起作用。 I also tried
我也试过了
temp = [np.linspace(step-1 , 1.0-step, subdivision) for i in range(D)]
grid = np.mgrid[temp]
But this doesn't work either since np.mgrid
accepts slices 但是这不起作用,因为
np.mgrid
接受切片
Instead of using complex
you can define the step size explicitly using real numbers. 您可以使用实数明确定义步长,而不是使用
complex
。 In my opinion this is more concise: 在我看来,这更简洁:
grid= np.mgrid[ step-1 : 1.0: step * 2,
step-1 : 1.0: step * 2,
step-1 : 1.0: step * 2]
Dissecting above snippet, we see that step-1 : 1.0: step * 2
defines a slice, and separating them by ,
creates a tuple of three slices, which is passed to np.mgrid.__getitem__
. 解剖上面的片段,我们看到
step-1 : 1.0: step * 2
定义了一个切片,并将它们分开,
创建了一个三个切片的元组,传递给np.mgrid.__getitem__
。
We can generalize this to n
dimensions by constructing a tuple of n
slices: 我们可以通过构造
n
切片的元组将它推广到n
维:
n = 3
grid= np.mgrid[tuple(slice(step - 1, 1, step * 2) for _ in range(n))]
As suggested by kazemakase , you should replace the "short hand" slicing notations step-1 : 1.0-step: complex(0,subdivision)
with an explicit call to slice
, and then combine it in a " tuple
generator": 正如kazemakase所建议的那样 ,你应该用一个显式调用
slice
来替换“short hand”切片符号step-1 : 1.0-step: complex(0,subdivision)
,然后将它组合成一个“ tuple
generator”:
D = 6
grid = np.mgrid[tuple(slice(step-1, 1.0-step, complex(0,subdivision)) for i in range(D))]
Results with a 6D grid. 使用6D网格的结果。
You can use meshgrid
and linspace
to do what you want. 您可以使用
meshgrid
和linspace
来执行您想要的操作。
import numpy as np
X1, X2, X3 = np.meshgrid(*[np.linspace(-1,1,5),
np.linspace(-1,1,5),
np.linspace(-1,1,5)])
For many dimensions, you can do 对于许多方面,你可以做到
D = 4
subdivision = 5
temp = [np.linspace(-1.0 , 1.0, subdivision) for i in range(D)]
res_to_unpack = np.meshgrid(*temp)
assert(len(res_to_unpack)==D)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.