numpy.meshgrid explanation
In [214]: nx, ny = (3, 2)In [215]: x = np.linspace(0, 1, nx)In [216]: xOut[216]: array([ 0. , 0.5, 1. ])In [217]: y = np.linspace(0, 1, ny)In [218]: yOut[218]: array([ 0., 1.])
Using unpacking to better see the 2 arrays produced by meshgrid
:
In [225]: X,Y = np.meshgrid(x, y)In [226]: XOut[226]: array([[ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ]])In [227]: YOut[227]: array([[ 0., 0., 0.], [ 1., 1., 1.]])
and for the sparse version. Notice that X1
looks like one row of X
(but 2d). and Y1
like one column of Y
.
In [228]: X1,Y1 = np.meshgrid(x, y, sparse=True)In [229]: X1Out[229]: array([[ 0. , 0.5, 1. ]])In [230]: Y1Out[230]: array([[ 0.], [ 1.]])
When used in calculations like plus and times, both forms behave the same. That's because of numpy's
broadcasting.
In [231]: X+YOut[231]: array([[ 0. , 0.5, 1. ], [ 1. , 1.5, 2. ]])In [232]: X1+Y1Out[232]: array([[ 0. , 0.5, 1. ], [ 1. , 1.5, 2. ]])
The shapes might also help:
In [235]: X.shape, Y.shapeOut[235]: ((2, 3), (2, 3))In [236]: X1.shape, Y1.shapeOut[236]: ((1, 3), (2, 1))
The X
and Y
have more values than are actually needed for most uses. But usually there isn't much of penalty for using them instead the sparse versions.
Your linear spaced vectors x
and y
defined by linspace
use 3 and 2 points respectively.
These linear spaced vectors are then used by the meshgrid function to create a 2D linear spaced point cloud. This will be a grid of points for each of the x
and y
coordinates. The size of this point cloud will be 3 x 2.
The output of the function meshgrid
creates an indexing matrix that holds in each cell the x
and y
coordinates for each point of your space.
This is created as follows:
# dummydef meshgrid_custom(x,y):xv = np.zeros((len(x),len(y)))yv = np.zeros((len(x),len(y)))for i,ix in zip(range(len(x)),x): for j,jy in zip(range(len(y)),y): xv[i,j] = ix yv[i,j] = jyreturn xv.T, yv.T
So, for example the point at the location (1,1) has the coordinates:
x = xv_1[1,1] = 0.5
y = yv_1[1,1] = 1.0