NumPy Lesson 27 – Meshgrid | Dataplexa

Meshgrid in NumPy

In numerical computing and scientific applications, we often need to work with coordinate grids instead of single arrays. NumPy provides the meshgrid function to create such coordinate matrices easily.

Meshgrid is commonly used in mathematics, simulations, visualizations, and machine learning preprocessing.


What Is Meshgrid?

meshgrid takes one-dimensional arrays and converts them into two-dimensional coordinate matrices.

These matrices represent all possible combinations of the input values.


Why Meshgrid Is Useful

  • Creating coordinate systems
  • Evaluating functions over a grid
  • Surface and contour plotting
  • Mathematical simulations

Basic Example of Meshgrid

Let’s start with two simple arrays representing X and Y values.

import numpy as np

x = np.array([1, 2, 3])
y = np.array([10, 20])

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

print("X grid:")
print(X)

print("Y grid:")
print(Y)

Output:

X grid:
[[1 2 3]
 [1 2 3]]

Y grid:
[[10 10 10]
 [20 20 20]]

Each grid represents how values are repeated to form all coordinate pairs.


Understanding the Output

The X grid repeats the x values across rows.

The Y grid repeats the y values down columns.

Together, they represent every possible (x, y) coordinate.


Evaluating a Function Using Meshgrid

Meshgrid is often used to compute functions over a grid.

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

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

Z = X + Y
print(Z)

Output:

[[ 0  1  2]
 [10 11 12]
 [20 21 22]]

Each element in Z is computed using corresponding values from X and Y.


Meshgrid Shapes

The shape of the output depends on the length of the input arrays.

  • If x has length n
  • If y has length m
  • Resulting grids have shape (m, n)

Using Meshgrid with linspace

Meshgrid is often combined with linspace for smooth grids.

x = np.linspace(0, 1, 5)
y = np.linspace(0, 2, 4)

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

Output:

(4, 5) (4, 5)

This is widely used in numerical analysis and simulations.


Common Mistakes

  • Confusing row and column repetition
  • Forgetting that meshgrid returns copies
  • Using meshgrid when broadcasting alone is enough

Practice Exercise

Task

  • Create x values from 0 to 5
  • Create y values from 0 to 3
  • Use meshgrid to compute Z = X × Y

What’s Next?

In the next lesson, you will learn about Numerical Techniques and how NumPy is used to solve mathematical problems efficiently.