numpy.meshgrid explanation
<p>Could someone care to explin the <code>meshgrid</code> method ? I cannot wrap my mind around it. The example is from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html#numpy.meshgrid" rel="nofollow">SciPy</a> site:</p>

<pre><code>import numpy as np

nx, ny = (3, 2)
x = np.linspace(0, 1, nx)
print ("x =", x)

y = np.linspace(0, 1, ny)
print ("y =", y)

xv, yv = np.meshgrid(x, y)
print ("xv_1 =", xv)
print ("yv_1 =",yv)


xv, yv = np.meshgrid(x, y, sparse=True)  # make sparse output arrays
print ("xv_2 =", xv)

print ("yv_2 =", yv)
</code></pre>

<p>Printout is :</p>

<pre><code>x = [ 0.   0.5  1. ]
y = [ 0.  1.]
xv_1 = [[ 0.   0.5  1. ]
 [ 0.   0.5  1. ]]
yv_1 = [[ 0.  0.  0.]
 [ 1.  1.  1.]]
xv_2 = [[ 0.   0.5  1. ]]
yv_2 = [[ 0.]
 [ 1.]]
</code></pre>

<p>Why are arrays xv_1 and yv_1 formed like this ? Ty :)</p>

<pre><code>In [214]: nx, ny = (3, 2)
In [215]: x = np.linspace(0, 1, nx)
In [216]: x
Out[216]: array([ 0. ,  0.5,  1. ])
In [217]: y = np.linspace(0, 1, ny)
In [218]: y
Out[218]: array([ 0.,  1.])
</code></pre>

<p>Using unpacking to better see the 2 arrays produced by <code>meshgrid</code>:</p>

<pre><code>In [225]: X,Y = np.meshgrid(x, y)
In [226]: X
Out[226]: 
array([[ 0. ,  0.5,  1. ],
       [ 0. ,  0.5,  1. ]])
In [227]: Y
Out[227]: 
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]])
</code></pre>

<p>and for the sparse version.  Notice that <code>X1</code> looks like one row of <code>X</code> (but 2d).  and <code>Y1</code> like one column of <code>Y</code>.</p>

<pre><code>In [228]: X1,Y1 = np.meshgrid(x, y, sparse=True)
In [229]: X1
Out[229]: array([[ 0. ,  0.5,  1. ]])
In [230]: Y1
Out[230]: 
array([[ 0.],
       [ 1.]])
</code></pre>

<p>When used in calculations like plus and times, both forms behave the same. That's because of <code>numpy's</code> broadcasting.</p>

<pre><code>In [231]: X+Y
Out[231]: 
array([[ 0. ,  0.5,  1. ],
       [ 1. ,  1.5,  2. ]])
In [232]: X1+Y1
Out[232]: 
array([[ 0. ,  0.5,  1. ],
       [ 1. ,  1.5,  2. ]])
</code></pre>

<p>The shapes might also help:</p>

<pre><code>In [235]: X.shape, Y.shape
Out[235]: ((2, 3), (2, 3))
In [236]: X1.shape, Y1.shape
Out[236]: ((1, 3), (2, 1))
</code></pre>

<p>The <code>X</code> and <code>Y</code> 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.</p>

python numpy