NumPy meshgrid() in python

Share this article

In NumPy, meshgrid() is a function that creates a coordinate matrix (grid) from two 1-D arrays. It’s commonly used in mathematical functions, simulations, and visualizations to create 2-D or multi-dimensional grids, which can then be used to evaluate functions at every point on the grid.

Example

import numpy as np

x = np.array([1, 2, 3])
y = np.array([4, 5])

X, Y = np.meshgrid(x, y)

print(X)
# Output:
# [[1 2 3]
#  [1 2 3]]

print(Y)
# Output:
# [[4 4 4]
#  [5 5 5]]

What it does

meshgrid() takes two 1-D arrays (x and y in this case) and generates two 2-D matrices. The first matrix (X) contains copies of the x array across rows, and the second matrix (Y) contains copies of the y array across columns. This forms a grid of coordinate pairs that can be used in further calculations.

Examples

Example 1: Creating a simple 2-D grid

x = np.array([0, 1, 2])
y = np.array([3, 4])

X, Y = np.meshgrid(x, y)

print(X)
# Output:
# [[0 1 2]
#  [0 1 2]]

print(Y)
# Output:
# [[3 3 3]
#  [4 4 4]]

Here, the x values are repeated across rows in X, while the y values are repeated across columns in Y. This creates a coordinate grid that pairs every x with every y.

Example 2: Using meshgrid for function evaluation

x = np.linspace(-2, 2, 5)
y = np.linspace(-2, 2, 5)

X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2

print(Z)
# Output:
# [[8. 5. 4. 5. 8.]
#  [5. 2. 1. 2. 5.]
#  [4. 1. 0. 1. 4.]
#  [5. 2. 1. 2. 5.]
#  [8. 5. 4. 5. 8.]]

In this example, meshgrid() creates a grid from x and y, and then we evaluate the function ( Z = X^2 + Y^2 ) at every grid point. This is often used in plotting 3D surfaces.

Example 3: Creating a 3-D grid

x = np.array([1, 2])
y = np.array([3, 4])
z = np.array([5, 6])

X, Y, Z = np.meshgrid(x, y, z, indexing='ij')

print(X.shape)  # Output: (2, 2, 2)
print(Y.shape)  # Output: (2, 2, 2)
print(Z.shape)  # Output: (2, 2, 2)

When three 1-D arrays are provided, meshgrid() can generate a 3-D grid, which is useful for higher-dimensional function evaluations and simulations.

Example 4: Changing the indexing mode

x = np.array([0, 1])
y = np.array([0, 1])

X, Y = np.meshgrid(x, y, indexing='ij')

print(X)
# Output:
# [[0 0]
#  [1 1]]

print(Y)
# Output:
# [[0 1]
#  [0 1]]

By setting the indexing parameter to 'ij', the output changes the way the grid is indexed. This can be important when working in different coordinate systems.