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 do I convert numpy mgrid function as a function?

Here is the way how numpy.mgrid is used.

grid = np.mgrid[x1:y1:100j , x2:y2:100j, ..., xn:yn:100j]

However, I find this structure very irritating. Therefore, I would like to create function f which works as follows:

f([(x1,y1,100),...,(xn,yn,100)]) = np.mgrid[x1:y1:100j , x2:y2:100j, ..., xn:yn:100j]

How can I create f?

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

(Here is the source code for np.mgrid)

>Solution :

Just loop over each item passed to f and make a slice out of it with slice, and to get 100j from 100, multiply 100 by 1j:

def f(items):
    slices = [slice(i[0], i[1], 1j * i[2]) for i in items]
    return np.mgrid[slices]

Output:

>>> np.all( f([(1,2,5), (2,3,5)]) == np.mgrid[1:2:5j, 2:3:5j] )
True

You could make calling the function even simpler by using *items instead of items:

def f(*items):
    slices = [slice(i[0], i[1], 1j * i[2]) for i in items]
    return np.mgrid[slices]

Output:

>>> np.all( f([1,2,5], [2,3,5]) == np.mgrid[1:2:5j, 2:3:5j] )
True
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