Matlab - Python meshgrid vs. ndgrid

When working with large grids, the grid itself can consume considerable memory. Large grids can require more advanced techniques like working with interpolants and using sparse grids. Many grids that aren’t too large can use common functions like “meshgrid” to make certain plotting or linear algebra operations easier. Matlab and Python (Numpy) can readily work with these data structures. We show the differences and similarities to allow understanding and translating code between Matlab and Python.

Matlab

Matlab meshgrid and ndgrid generate distinct data for the first two dimensions, but other dimensions remain the same. This is due to meshgrid() being intended for plotting, and ndgrid() intended for matrix operations.

[x,y] = meshgrid([1,2], [1,2])

x =
     1     2
     1     2

y =
     1     1
     2     2
[x,y] = ndgrid([1,2], [1,2])

x =
     1     1
     2     2

y =
     1     2
     1     2

Python Numpy

Numpy is used for most array computation in Python–many Python numerical libraries use Numpy internally. Numpy has additional advanced grid generation functions numpy.mgrid() and numpy.ogrid()–here we will focus on numpy.meshgrid. numpy.meshgrid also has copy=False and sparse=True options that allow conserving memory. For simplicity, we will use the defaults, which is a dense copied mesh.

Equivalent to Matlab meshgrid():

x,y = numpy.meshgrid([1,2], [1,2], indexing='xy')

>>> x
array([[1, 2],
       [1, 2]])
>>> y
array([[1, 1],
       [2, 2]])

Equivalent to Matlab ndgrid():

x,y = numpy.meshgrid([1,2], [1,2], indexing='ij')

>>> x
array([[1, 1],
       [2, 2]])
>>> y
array([[1, 2],
       [1, 2]])