What is the numpy.meshgrid() function in Python?
Overview
The numpy.meshgrid() function in Python is used to return the coordinate matrices from given coordinate vectors.
Syntax
numpy.meshgrid(*xi, copy=True, sparse=False, indexing='xy')
Parameter values
The numpy.meshgrid() function takes the following parameter values:
x1, x2,..., xn: these represent the 1-D arrays, which also represent the coordinates of a grid.indexing: this represents the default, Cartesian (xy), or matrix (ij) indexing of the output. This is optional.sparse: this takes a Boolean value. IfTrue, the shape of the returned coordinate array for dimensioniis reduced from(N1, ..., Ni, ..., Nn)to(1, ..., 1, Ni, 1, ..., 1). This is optional.copy: this takes a Boolean value. IfFalse, a view into the original arrays are returned in order to conserve memory. The default value isFalse. This is optional.
Return value
The numpy.meshgrid() function returns X1, X2,...XN arrays.
Code example
import numpy as np# creating the array_like objectsnx, ny = (2, 3)# implementing the linespace functionx = np.linspace(0, 1, nx)y = np.linspace(0, 1, ny)xv, yv = np.meshgrid(x, y, copy = True, sparse = False, indexing ='xy' )print(xv)print(yv)
Code explanation
Here is a line-by-line explanation of the code above:
- Line 1: We import the
numpylibrary. - Line 4: We create array_like objects
nxandny. - Line 7-8: Using the
linspace()function, we return evenly spaced numbers over a specified interval starting from0to1for thenxandnyarray-like objects. - Line 11: We implement the
meshgrid()function on the matricesxvandyv - Line 13-14: We print the matrices
xvandyv.