Lin Ma Lin Ma - 3 months ago 61
Python Question

confused by numpy meshgrid output

Using Python 2.7 with miniconda interpreter. I am confused by what means N-D coordinate in the following statements, and could anyone tell how in the below sample

xv
and
yv
are calculated, it will be great.

"Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn."

http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html

>>> nx, ny = (3, 2)
>>> x = np.linspace(0, 1, nx)
>>> y = np.linspace(0, 1, ny)
>>> xv, yv = meshgrid(x, y)
>>> xv
array([[ 0. , 0.5, 1. ],
[ 0. , 0.5, 1. ]])
>>> yv
array([[ 0., 0., 0.],
[ 1., 1., 1.]])


regards,
Lin

Answer

xv,yv are simply defined as:

xv = np.array([x for _ in y])
yv = np.array([y for _ in x]).T

so that for every index pair (i,j), you have

xv[i,j] = x[i]
yv[i,j] = y[j]

which is useful especially for plotting 2D maps.

Comments