How to generate n-dimensional mesh in python

I want to create an n-dimensional mesh.

For a 3D mesh, I have the following working code (which creates a 5X5X5 mesh between (-1,1)

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

grid = np.mgrid[step-1 : 1.0-step: complex(0,subdivision) for i in range(n)]

      

But that obviously doesn't work. I have also tried

temp = [np.linspace(step-1 , 1.0-step, subdivision) for i in range(D)]
grid = np.mgrid[temp]

      

But that won't work, since it np.mgrid

takes slices

+3


source to share


3 answers


Instead of using it, complex

you can explicitly define the step size using real numbers. In my opinion, this is more eloquent:

grid= np.mgrid[ step-1 : 1.0: step * 2,
                step-1 : 1.0: step * 2,
                step-1 : 1.0: step * 2]

      

Expanding the snippet above, we can see what step-1 : 1.0: step * 2

defines a slice and dividing it by ,

creates a tuple of three slices that is passed to np.mgrid.__getitem__

.



We can generalize this to dimensions n

by building a set of n

slices:

n = 3
grid= np.mgrid[tuple(slice(step - 1, 1, step * 2) for _ in range(n))]

      

+4


source


As suggested by kazemakase , you should replace the "short manual" slicing of notes with an step-1 : 1.0-step: complex(0,subdivision)

explicit call slice

and then concatenate it in a <<22> generator:

D = 6
grid = np.mgrid[tuple(slice(step-1, 1.0-step, complex(0,subdivision)) for i in range(D))]

      



Results with 6D grid.

+1


source


You can use meshgrid

and linspace

do whatever you want.

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 measurements, 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)

      

0


source







All Articles