Is there a multi-dimensional version of arange/linspace in numpy?

You can use np.mgrid for this, it’s often more convenient than np.meshgrid because it creates the arrays in one step:

import numpy as np
X,Y = np.mgrid[-5:5.1:0.5, -5:5.1:0.5]

For linspace-like functionality, replace the step (i.e. 0.5) with a complex number whose magnitude specifies the number of points you want in the series. Using this syntax, the same arrays as above are specified as:

X, Y = np.mgrid[-5:5:21j, -5:5:21j]

You can then create your pairs as:

xy = np.vstack((X.flatten(), Y.flatten())).T

As @ali_m suggested, this can all be done in one line:

xy = np.mgrid[-5:5.1:0.5, -5:5.1:0.5].reshape(2,-1).T

Best of luck!

Leave a Comment