Numpy ravel does not revert meshgrid() in 3 dimensions

Viewed 26

I am trying to get rid of these ugly for loops in my code but I can't recover the same behaviour when using np.meshgrid() and np.flatten(). Here is a minimal example illustrating the problem :

import numpy as np

a = np.arange(0,10)
b = np.arange(0,10)
c = np.arange(0,10)

mesh_tuple=np.meshgrid(*[a,b,c])
meshlist = []
for i in range(len(mesh_tuple)):
    meshlist.append(mesh_tuple[i].flatten())

meshlist = np.asarray(meshlist)

list0, list1, list2 = [], [], []
for i0, p0 in enumerate(a):
    for i1, p1 in enumerate(b):
        for i2, p2 in enumerate(c):
            list0.append(p0)
            list1.append(p1)
            list2.append(p2)

list0 = np.asarray(list0)
list1 = np.asarray(list1)
list2 = np.asarray(list2)

print(np.array_equal(list0, meshlist[0,:]))
print(np.array_equal(list1, meshlist[1,:]))
print(np.array_equal(list2, meshlist[2,:]))

print(np.array_equal(list0, meshlist[1,:]))
print(np.array_equal(list1, meshlist[0,:]))
print(np.array_equal(list2, meshlist[2,:]))

and this return :

False
False
True
True
True
True

Of course, I could swap the first two indices but that would only fix the problem in 3 dimensions. Does anyone know how to generalise this to N-dimension ?

Thank you,

1 Answers

mesh_tuple=np.meshgrid(*[a,b,c], indexing='ij')

For reasons that aren't obvious, meshgrid swaps the first two arrays when generating its indices. indexing='ij' tells it to do what you intended.

Related