[Numpy-discussion] Create a n-D grid; meshgrid alternative

Nathaniel Smith njs at pobox.com
Sun May 10 20:44:33 EDT 2015


On Sun, May 10, 2015 at 4:40 AM, Stefan Otte <stefan.otte at gmail.com> wrote:
> Hey,
>
> quite often I want to evaluate a function on a grid in a n-D space.
> What I end up doing (and what I really dislike) looks something like this:
>
>   x = np.linspace(0, 5, 20)
>   M1, M2 = np.meshgrid(x, x)
>   X = np.column_stack([M1.flatten(), M2.flatten()])
>   X.shape  # (400, 2)
>
>   fancy_function(X)
>
> I don't think I ever used `meshgrid` in any other way.
> Is there a better way to create such a grid space?

I feel like our "house style" has moved away from automatic
flattening, and would maybe we should be nudging people towards
something more like

  # using proposed np.stack from pull request #5605
  X = np.stack(np.meshgrid(x, x), axis=-1)
  assert X.shape == (20, 20, 2)
  fancy_function(X)  # vectorized to accept any array with shape (..., 2)

-n

-- 
Nathaniel J. Smith -- http://vorpus.org



More information about the NumPy-Discussion mailing list