Mesh grid functions in Python (meshgrid mgrid ogrid ndgrid)

Question:

I’m looking for a clear comparison of meshgrid-like functions. Unfortunately I don’t find it!

Numpy http://docs.scipy.org/doc/numpy/reference/ provides

  • mgrid

  • ogrid

  • meshgrid

Scitools http://hplgit.github.io/scitools/doc/api/html/index.html provides

  • ndgrid

  • boxgrid

Ideally a table summarizing all this would be perfect!

Asked By: scls

||

Answers:

numpy.meshgrid is modelled after Matlab’s meshgrid command. It is used to vectorise functions of two variables, so that you can write

x = numpy.array([1, 2, 3])
y = numpy.array([10, 20, 30]) 
XX, YY = numpy.meshgrid(x, y)
ZZ = XX + YY

ZZ => array([[11, 12, 13],
             [21, 22, 23],
             [31, 32, 33]])

So ZZ contains all the combinations of x and y put into the function. When you think about it, meshgrid is a bit superfluous for numpy arrays, as they broadcast. This means you can do

XX, YY = numpy.atleast_2d(x, y)
YY = YY.T # transpose to allow broadcasting
ZZ = XX + YY

and get the same result.

mgrid and ogrid are helper classes which use index notation so that you can create XX and YY in the previous examples directly, without having to use something like linspace. The order in which the output are generated is reversed.

YY, XX = numpy.mgrid[10:40:10, 1:4]
ZZ = XX + YY # These are equivalent to the output of meshgrid

YY, XX = numpy.ogrid[10:40:10, 1:4]
ZZ = XX + YY # These are equivalent to the atleast_2d example

I am not familiar with the scitools stuff, but ndgrid seems equivalent to meshgrid, while BoxGrid is actually a whole class to help with this kind of generation.

Answered By: chthonicdaemon

np.mgrid and np.meshgrid() do the same thing but the first and the second axis are swapped:

# 3D
d1, d2, d3 = np.mgrid[0:10, 0:10, 0:10]
d11, d22, d33 = np.meshgrid(np.arange(10),np.arange(10),np.arange(10))
np.array_equal(d1,d11)

yields False. Just swap the first two dimensions:

d11 = np.transpose(d11,[1,0,2])
np.array_equal(d1,d11)

yields True.

This dimension swapping needs to be done for all three arrays d11, d22 and d33.

Answered By: dopexxx
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.