numpy.mgrid
numpy.mgrid
can be used to create meshgrid by using slices.
np.mgrid[0:5, 0:5]
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
This is equivalent to,
np.meshgrid(np.arange(5), np.arange(5), indexing="ij")
[array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]]),
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])]
np.mgrid
uses matrix indexing system.
We can provide steps to np.mgrid
as it is working with slices.
np.mgrid[0:5:2, 0:5:2]
array([[[0, 0, 0],
[2, 2, 2],
[4, 4, 4]],
[[0, 2, 4],
[0, 2, 4],
[0, 2, 4]]])
This is equivalent to,
np.meshgrid(np.arange(0, 5, 2), np.arange(0, 5, 2), indexing="ij")
[array([[0, 0, 0],
[2, 2, 2],
[4, 4, 4]]),
array([[0, 2, 4],
[0, 2, 4],
[0, 2, 4]])]
By providing complex number step to the slice, we can mimic np.linspace
method.
np.mgrid[0:5:4j, 0:5:4j]
array([[[0. , 0. , 0. , 0. ],
[1.66666667, 1.66666667, 1.66666667, 1.66666667],
[3.33333333, 3.33333333, 3.33333333, 3.33333333],
[5. , 5. , 5. , 5. ]],
[[0. , 1.66666667, 3.33333333, 5. ],
[0. , 1.66666667, 3.33333333, 5. ],
[0. , 1.66666667, 3.33333333, 5. ],
[0. , 1.66666667, 3.33333333, 5. ]]])
Which again can be done with np.meshgrid
.
np.meshgrid(np.linspace(0, 5, 4), np.linspace(0, 5, 4), indexing="ij")
[array([[0. , 0. , 0. , 0. ],
[1.66666667, 1.66666667, 1.66666667, 1.66666667],
[3.33333333, 3.33333333, 3.33333333, 3.33333333],
[5. , 5. , 5. , 5. ]]),
array([[0. , 1.66666667, 3.33333333, 5. ],
[0. , 1.66666667, 3.33333333, 5. ],
[0. , 1.66666667, 3.33333333, 5. ],
[0. , 1.66666667, 3.33333333, 5. ]])]