Skip to content

Commit 8f0f33b

Browse files
timhoffmrossbar
andauthored
DOC: Add explanation of a sparse mesh grid (numpy#19776)
* Add explanation of a spare mesh grid. Co-authored-by: Ross Barnowski <[email protected]>
1 parent e791b11 commit 8f0f33b

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

numpy/lib/function_base.py

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4276,7 +4276,13 @@ def meshgrid(*xi, copy=True, sparse=False, indexing='xy'):
42764276
42774277
.. versionadded:: 1.7.0
42784278
sparse : bool, optional
4279-
If True a sparse grid is returned in order to conserve memory.
4279+
If True the shape of the returned coordinate array for dimension *i*
4280+
is reduced from ``(N1, ..., Ni, ... Nn)`` to
4281+
``(1, ..., 1, Ni, 1, ..., 1)``. These sparse coordinate grids are
4282+
intended to be use with :ref:`basics.broadcasting`. When all
4283+
coordinates are used in an expression, broadcasting still leads to a
4284+
fully-dimensonal result array.
4285+
42804286
Default is False.
42814287
42824288
.. versionadded:: 1.7.0
@@ -4347,17 +4353,30 @@ def meshgrid(*xi, copy=True, sparse=False, indexing='xy'):
43474353
array([[0.],
43484354
[1.]])
43494355
4350-
`meshgrid` is very useful to evaluate functions on a grid.
4356+
`meshgrid` is very useful to evaluate functions on a grid. If the
4357+
function depends on all coordinates, you can use the parameter
4358+
``sparse=True`` to save memory and computation time.
4359+
4360+
>>> x = np.linspace(-5, 5, 101)
4361+
>>> y = np.linspace(-5, 5, 101)
4362+
>>> # full coorindate arrays
4363+
>>> xx, yy = np.meshgrid(x, y)
4364+
>>> zz = np.sqrt(xx**2 + yy**2)
4365+
>>> xx.shape, yy.shape, zz.shape
4366+
((101, 101), (101, 101), (101, 101))
4367+
>>> # sparse coordinate arrays
4368+
>>> xs, ys = np.meshgrid(x, y, sparse=True)
4369+
>>> zs = np.sqrt(xs**2 + ys**2)
4370+
>>> xs.shape, ys.shape, zs.shape
4371+
((1, 101), (101, 1), (101, 101))
4372+
>>> np.array_equal(zz, zs)
4373+
True
43514374
43524375
>>> import matplotlib.pyplot as plt
4353-
>>> x = np.arange(-5, 5, 0.1)
4354-
>>> y = np.arange(-5, 5, 0.1)
4355-
>>> xx, yy = np.meshgrid(x, y, sparse=True)
4356-
>>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
4357-
>>> h = plt.contourf(x, y, z)
4376+
>>> h = plt.contourf(x, y, zs)
43584377
>>> plt.axis('scaled')
4378+
>>> plt.colorbar()
43594379
>>> plt.show()
4360-
43614380
"""
43624381
ndim = len(xi)
43634382

0 commit comments

Comments
 (0)