Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
function
communitycreator

What is the numpy.meshgrid() function in Python?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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. If True, the shape of the returned coordinate array for dimension i is reduced from (N1, ..., Ni, ..., Nn) to (1, ..., 1, Ni, 1, ..., 1). This is optional.
  • copy: this takes a Boolean value. If False, a view into the original arrays are returned in order to conserve memory. The default value is False. This is optional.

Return value

The numpy.meshgrid() function returns X1, X2,...XN arrays.

Code example

import numpy as np
# creating the array_like objects
nx, ny = (2, 3)
# implementing the linespace function
x = 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 numpy library.
  • Line 4: We create array_like objects nx and ny.
  • Line 7-8: Using the linspace() function, we return evenly spaced numbers over a specified interval starting from 0 to 1 for the nx and ny array-like objects.
  • Line 11: We implement the meshgrid() function on the matrices xv and yv
  • Line 13-14: We print the matrices xv and yv.

RELATED TAGS

numpy
python
function
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring