w3resource

NumPy: numpy.ogrid() function

numpy.ogrid() function

The numpy.ogrid() function is used to create multi-dimensional open grids, where the start, end, and number of points for each dimension can be specified.
The dimension and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive.
However, if the step length is a complex number (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value is inclusive.

Syntax:

numpy.ogrid = <numpy.lib.index_tricks.nd_grid object>

Return value:

mesh-grid 'ndarrays' with only one dimension :math:'neq 1'.

Example: Creating open multi-dimensional grids using ogrid

>>> import numpy as np
>>> from numpy import ogrid
>>> ogrid[-1:1:4j]
array([-1.        , -0.33333333,  0.33333333,  1.        ])

In the above code, we create a 1-dimensional open grid with the start value of -1, end value of 1 and 4j points, which means that the array will contain 4 values, evenly spaced in the interval from -1 to 1.

Example: Creating a meshgrid using the ogrid function in numpy

>>> import numpy as np
>>> from numpy import ogrid
>>> ogrid[0:4,0:4]
[array([[0],
       [1],
       [2],
       [3]]), array([[0, 1, 2, 3]])]

In the above example we create a meshgrid of size 4x4 using the ogrid function, which returns a list of two arrays.
The first array represents the values along the vertical axis of the meshgrid and the second array represents the values along the horizontal axis of the meshgrid, which is obtained in a similar way as the first array. Together, the two arrays form a 4x4 meshgrid with values [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]].

Python - NumPy Code Editor:

Previous: mgrid()
Next: Building matrices diag()



Follow us on Facebook and Twitter for latest update.