1

similar to the question here I have three arbitrary 1D arrays, for example:

x_p = np.array((0.0,1.1, 2.2, 3.3, 4.4))
y_p = np.array((5.5,6.6,7.7))
z_p = np.array((8.8, 9.9))

I need

points = np.array([[0.0, 5.5, 8.8],
                   [1.1, 5.5, 8.8],
                   [2.2, 5.5, 8.8],
                   ...
                   [4.4, 7.7, 9.9]])

1) with the first index changing fastest.2) points are float coordinates, not integer index. 3) I noticed from version 1.7.0, numpy.meshgrid has changed behavior with default indexing='xy' and need to use

np.vstack(np.meshgrid(x_p,y_p,z_p,indexing='ij')).reshape(3,-1).T

to get the result points with last index changing fast, which is not I want.(It was mentioned only from 1.7.0,meshgrid supports dimension>2, I didn't check)

george andrew
  • 451
  • 4
  • 12

2 Answers2

1

You might permute axes with np.transpose to achieve the output in that desired format -

np.array(np.meshgrid(x_p, y_p, z_p)).transpose(3,1,2,0).reshape(-1,3)

Sample output -

In [104]: np.array(np.meshgrid(x_p, y_p, z_p)).transpose(3,1,2,0).reshape(-1,3)
Out[104]: 
array([[ 0. ,  5.5,  8.8],
       [ 1.1,  5.5,  8.8],
       [ 2.2,  5.5,  8.8],
       [ 3.3,  5.5,  8.8],
       [ 4.4,  5.5,  8.8],
       [ 0. ,  6.6,  8.8],
       [ 1.1,  6.6,  8.8],
       [ 2.2,  6.6,  8.8],
       [ 3.3,  6.6,  8.8],
       [ 4.4,  6.6,  8.8],
       [ 0. ,  7.7,  8.8],
       [ 1.1,  7.7,  8.8],
       ....
       [ 3.3,  7.7,  9.9],
       [ 4.4,  7.7,  9.9]])
Divakar
  • 218,885
  • 19
  • 262
  • 358
1

I found this with some trial and error.

I think the ij v xy indexing has been in meshgrid forever (it's the sparse parameter that's newer). It just affects the order of the 3 returned elements.

To get x_p varying fastest I put it last in the argument list, and then used a ::-1 to reverse column order at the end.

I used stack to join the arrays on a new axis at the end, so I don't need to transpose. But the reshaping and transpose's are all cheap (time wise). So they can be used in any combination that works and is understandable.

In [100]: np.stack(np.meshgrid(z_p, y_p, x_p, indexing='ij'),3).reshape(-1,3)[:,::-1]
Out[100]: 
array([[ 0. ,  5.5,  8.8],
       [ 1.1,  5.5,  8.8],
       [ 2.2,  5.5,  8.8],
       [ 3.3,  5.5,  8.8],
       [ 4.4,  5.5,  8.8],
       [ 0. ,  6.6,  8.8],
       ...
       [ 2.2,  7.7,  9.9],
       [ 3.3,  7.7,  9.9],
       [ 4.4,  7.7,  9.9]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353