np.meshgrid and np.mgrid / np.ogrid build coordinate arrays for evaluating functions over 2D grids—common in plotting and PDE-style computations.
meshgrid basics
import numpy as np
x = np.array([0, 1, 2])
y = np.array([0, 10, 20])
X, Y = np.meshgrid(x, y)
print(X.shape, Y.shape)
Evaluating functions
import numpy as np
x = np.linspace(-1, 1, 3)
y = np.linspace(-1, 1, 3)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
print(Z)
ogrid for memory
np.ogrid[0:5, 0:5] returns open grids that broadcast without full dense coordinate arrays—handy for large domains.
Important interview questions and answers
- Q: meshgrid indexing='ij'?
A: Matrix indexing (row, col) vs default 'xy' Cartesian plotting convention. - Q: Used in Matplotlib?
A: contourf and pcolormesh accept X, Y coordinate grids from meshgrid.
Self-check
- Create 2D grid from x=[0,1] and y=[0,10].
- Compute Z = X + Y on a small meshgrid.
Tip: Use ogrid for large domains to save memory.
Interview prep
- Purpose?
Build coordinate grids for evaluating f(x,y) or plotting.
- ogrid?
Open grid—broadcast-friendly, memory efficient.