Python – numpy.meshgrid


numpy.meshgrid() is used to return coordinate matrices from coordinate vectors. Its syntax is as follows −

numpy.meshgrid(*xi, **kwargs)

Parameters

Meshgrid can accept the following parameters −

  • x1, x2, …, xn − It represents the coordinates of a grid.

  • indexing − It is an optional parameter which defines the Cartesian 'xy' by default and matrix 'ij' index of output.

  • sparse − It is an optional parameter. If we like to use sparse grid for conserving memory, then we have to set this parameter to True. By default, it is False.

  • copy − It returns a copy of the original array for conversing memory when the parameter is True. By default, it is False.

Example 1

Let us consider the following example −

# Import numpy
import numpy as np

# input array
x = np.array([1,2,3,4,5])
y = np.array([11, 12, 13, 14, 15])
print("Input x :\n", x)
print("Input y :\n", y)

# meshgrid() function
xx, yy = np.meshgrid(x, y, sparse=True)
print("Meshgrid of X:", xx)
print("Meshgrid of Y:\n", yy)

Output

It will generate the following output −

Input x :
 [1 2 3 4 5]
Input y :
 [11 12 13 14 15]
Meshgrid of X: [[1 2 3 4 5]]
Meshgrid of Y:
 [[11]
 [12]
 [13]
 [14]
 [15]]

Example 2

Let us take another example. It highlights the difference between linspace and meshgrid.

# Import numpy
import numpy as np

# linspace function
a = np.linspace(3, 4, 4)
b = np.linspace(4, 5, 6)
print("linspace of a :", a)
print("linspace of b :", b)

# meshgrid function
xa, xb = np.meshgrid(a, b)
print("Meshgrid of xa :\n", xa)
print("Meshgrid of xb :\n", xb)

Output

The above program will generate the following output −

linspace of a : [3.          3.33333333 3.66666667 4.       ]
linspace of b : [4. 4.2 4.4 4.6 4.8 5. ]
Meshgrid of xa :
 [[3.          3.33333333 3.66666667 4.       ]
 [3.         3.33333333 3.66666667 4.       ]
 [3.          3.33333333 3.66666667 4.       ]
 [3.          3.33333333 3.66666667 4.       ]
 [3.          3.33333333 3.66666667 4.       ]
 [3.          3.33333333 3.66666667 4.       ]]
Meshgrid of xb :
 [[4. 4. 4. 4. ]
 [4.2 4.2 4.2 4.2]
 [4.4 4.4 4.4 4.4]
 [4.6 4.6 4.6 4.6]
 [4.8 4.8 4.8 4.8]
 [5. 5. 5. 5. ]]

Updated on: 03-Mar-2022

813 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements