Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a variable number of dimensions for mgrid

I would like to create a meshgrid of variable dimensions by specifying the dimensions with a variable i.e. specifying dim=2, rather than manually changing the expression as in the example below to set a 2D mesh grid.

How would I implement a wrapper function for this?

The problem stems from not being familiar with the syntax that mgrid uses (index_tricks).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import numpy as np

mgrid = np.mgrid[
                  -5:5:5j,
                  -5:5:5j,
                ]

Observed documentation for mgrid, but there seems to be no info on setting the number of dimensions with a variable.

>Solution :

You can create a tuple containing the slice manually, and repeat it some number of times:

import numpy as np

num_dims = 2

mgrid = np.mgrid[(slice(-5, 5, 5j),) * num_dims]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading