Coordinate grids let a calculation evaluate every pair of x and y values without nested Python loops. NumPy np.meshgrid() expands one-dimensional coordinate arrays into matching arrays for plotting, surface formulas, and vectorized simulations.
By default, np.meshgrid() uses Cartesian indexing=“xy”. With two input vectors, the returned arrays follow plotting order, so y values fill rows and x values fill columns. Matrix indexing=“ij” keeps the first output axis tied to the first input vector when later code expects input-order axes.
Dense coordinate grids allocate a full array for each coordinate direction. Sparse grids keep each coordinate array narrow and rely on NumPy broadcasting during the calculation, which matters when the coordinate ranges grow but the final expression can still be vectorized.
Related: Create linearly spaced values
Related: Create an array
import numpy as np x = np.array([0, 1, 2]) y = np.array([10, 20]) xx, yy = np.meshgrid(x, y, indexing="xy") surface = xx + yy ii, jj = np.meshgrid(x, y, indexing="ij") xs, ys = np.meshgrid(x, y, indexing="xy", sparse=True) sparse_surface = xs + ys assert xx.shape == (2, 3) assert yy.shape == (2, 3) assert surface.shape == (2, 3) assert ii.shape == (3, 2) assert jj.shape == (3, 2) assert xs.shape == (1, 3) assert ys.shape == (2, 1) assert np.array_equal(surface, sparse_surface) print("xy grid shapes:", xx.shape, yy.shape) print("xx:") print(xx) print("yy:") print(yy) print("surface:") print(surface) print("ij grid shapes:", ii.shape, jj.shape) print("sparse grid shapes:", xs.shape, ys.shape) print("sparse matches dense:", np.array_equal(surface, sparse_surface))
The assertions stop the script if a future edit changes the documented grid shapes or sparse-grid result.
$ python meshgrid-create.py xy grid shapes: (2, 3) (2, 3) xx: [[0 1 2] [0 1 2]] yy: [[10 10 10] [20 20 20]] surface: [[10 11 12] [20 21 22]] ij grid shapes: (3, 2) (3, 2) sparse grid shapes: (1, 3) (2, 1) sparse matches dense: True
The xx and yy arrays both have shape (2, 3) because the y vector has two values and the x vector has three values. Each position in surface comes from one x-y coordinate pair.
The ij grid shapes row is (3, 2) for both arrays, so the first axis follows x and the second axis follows y.
The sparse arrays keep shapes (1, 3) and (2, 1), and the final line confirms their broadcasted sum matches the dense surface array.
Related: Calculate with broadcasting