Meshgrid

Numpy meshgrid creates grid matrices from the input arrays. These matrices are also called coordinate matrices.

figure: From microsoft excel. Showing good example of meshgrid.
figure: From microsoft excel. Showing good example of meshgrid.
a = np.arange(5)
X, Y = np.meshgrid(a, a)
X
 
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
 
Y
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4]])

These matrices allow to make all the possible combinations for the input arrays elements. We can do this by placing these x and y matrices on top one another.

for i in a:
   for j in a:
       print((X[i,j], Y[i,j]))
 
 
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(4, 0)
(0, 1)
(1, 1)
(2, 1)
(3, 1)
(4, 1)
(0, 2)
(1, 2)
(2, 2)
(3, 2)
(4, 2)
(0, 3)
(1, 3)
(2, 3)
(3, 3)
(4, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)

Note

Using Uppercase variable name for output return from meshgrid is usually a preferred, given using small case in python conventions.

By default np.meshgrid uses Cartesian system for indexing ( system). This can be changed to matrix indexing .

np.meshgrid([1, 2], [4, 5])
[array([[1, 2],
        [1, 2]]),
 array([[4, 4],
        [5, 5]])]
 
 
np.meshgrid([1, 2], [4, 5], indexing="ij")
[array([[1, 1],
        [2, 2]]),
 array([[4, 5],
        [4, 5]])]

Applications for Meshgrid

  • Meshgrid is used to create coordinate matrices to model a grid.
  • Model 2D mathematical functions.
  • etc.

Refer notebook.

References

  1. https://www.udacity.com/blog/2021/10/numpy-np-meshgrid-tutorial-for-beginners.html
  2. https://thepythoncodingbook.com/2022/05/28/numpy-meshgrid