Gice

Technology and General Blog

This post will show what a meshgrid is and how it can be created and used in python.

A meshgrid is a rectangular grid of values made out of coordinate vectors. It is also that the values in the meshgrid are a function of the coordinate vectors.
Let’s say you want to create a meshgrid out of the coordinate vectors x and y. The naive way to do it is create a new rectangular grid and assign the values of the grid by evaluating the function at each point of the meshgrid. The following code illustrated the naive way:

Meshgrid Naive Way:

x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 2, 3, 4, 5]
z = [[0 for j in range(len(y))] for i in range(x)]
for i in range(len(x)):
for j in range(len(y)):
z[i, j] = func(x[i], y[i]) The drawbacks of this approach are that it is tedious, and handling large coordinate vectors takes more time. The python library numpy for scientific computing helps in creating a meshgrid more efficiently. For creating a meshgrid, we will be using the function numpy.meshgrid. Here is the same solution using numpy.

\$ python3
Python 3.8.5 (default, Mar  8 2021, 13:02:45)
[GCC 9.3.0] on linux2
>>> import numpy as np
>>> x = np.linspace(0, 6, 3)
>>> x
array([0., 3., 6.])
>>> y = np.linspace(1, 7, 3)
>>> y
array([1., 4., 7.])
>>> xx, yy = np.meshgrid(x, y)
>>> xx
array([[0., 3., 6.],
[0., 3., 6.],
[0., 3., 6.]])
>>> xx.shape
(3, 3) Numpy’s vectorized operations make it faster than python loops. Vectorizations help by delegating the looping operation to highly optimized C code internally and making it faster. It also expresses operations on the entire arrays rather than the individual elements of the arrays.

Evaluating a function over the meshgrid is very easy. All we need to do is just call the function. We will also plot the evaluated function here by making a contour plot using matplotlib. Continuing from the previous example, >>> z = np.sin(xx**2 + yy**2)
>>> import matplotlib.pyplot as plt
>>> plt.figure(figsize=(10, 6))
>>> plt.contourf(xx, yy, z)
>>> plt.colorbar()
>>> plt.show() If the array x and y are too big, then the array xx and yy might take a lot of space. This can be optimized using the option sparse=True.

>>> x = np.linspace(0, 5, 6)
>>> y = np.linspace(0, 5, 6)
>>> xx, yy = np.meshgrid(x, y, sparse=False) #default
>>> xx
array([[0., 1., 2., 3., 4., 5.],
[0., 1., 2., 3., 4., 5.],
[0., 1., 2., 3., 4., 5.],
[0., 1., 2., 3., 4., 5.],
[0., 1., 2., 3., 4., 5.],
[0., 1., 2., 3., 4., 5.]])
>>> xx.shape
(6, 6)

>>> xx, yy = np.meshgrid(x, y, sparse=True) #default
>>> xx
array([[0., 1., 2., 3., 4., 5.]])
>>> xx.shape
(1, 6) 