How to convert arrays of x,y,z coordinates to 3D path in numpy
How's this look?
import numpy as npdef path_3d_numpy(x, y, z): coords = np.stack(np.meshgrid(x, y, z), axis=-1) # shape = (nx, ny, nz, 3) coords[1::2,:,:] = coords[1::2,::-1,:] coords[:,1::2,:] = coords[:,1::2,::-1] return coords.reshape(-1, 3) # flatten out the other axes
Doesn't iterate the points in quite the same order as yours, but you could fix that simply by swapping some indices around
Similarly, your 2d case could be written as
def path_2d_numpy(x, y): coords = np.stack(np.meshgrid(x, y), axis=-1) coords[1::2] = coords[1::2,::-1] return coords.reshape(-1, 2)
For some real overkill, you can extend this to N dimensions:
def path_nd(*args): coords = np.stack(np.meshgrid(*args), axis=-1) N = len(args) axes = np.arange(N) for i in range(N-1): # the last axis isn't part of our mesh, so don't roll it rolled_axes = tuple(np.roll(axes, -i)) + (N,) rolled_view = np.transpose(coords, rolled_axes) rolled_view[1::2,:] = rolled_view[1::2,::-1] return coords.reshape(-1, N)