How to perform an ND coordinate sweep using numpy meshgrid

后端 未结 3 1525
攒了一身酷
攒了一身酷 2021-01-25 23:41

I want to create a grid of sampling points in 4 dimensions. I want the points to span from 0 to 10 with equal spacing in each direction. I tried a few iterations of np.mes

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-25 23:49

    meshgrid returns the coordinates in the corresponding arrays. In your case for 4 dimensions:

    xx, yy, zz, ww  = np.meshgrid(x, y, z, w)
    

    That means, xx will contains all the x coordinates while yy all the y coordinates and so on. Further more xx.shape == yy.shape == ... and is equal to the number of points on the grid.

    To get your desired result, might be stack:

    # point as rows 
    out = np.stack(np.meshgrid(*[x]*MD), axis=-1).reshape(-1, MD)
    
    array([[ 0.        ,  0.        ,  0.        ,  0.        ],
           [ 0.        ,  0.        ,  0.        ,  0.52631579],
           [ 0.        ,  0.        ,  0.        ,  1.05263158],
           ...,
           [10.        , 10.        , 10.        ,  8.94736842],
           [10.        , 10.        , 10.        ,  9.47368421],
           [10.        , 10.        , 10.        , 10.        ]])
    
    # or point as columns
    out = np.stack(np.meshgrid(*[x]*MD).reshape(MD, -1)
    
    array([[ 0.        ,  0.        ,  0.        , ..., 10.        , 10.        , 10.        ],
           [ 0.        ,  0.        ,  0.        , ..., 10.        , 10.        , 10.        ],
           [ 0.        ,  0.        ,  0.        , ..., 10.        , 10.        , 10.        ],
           [ 0.        ,  0.52631579,  1.05263158, ...,  8.94736842,  9.47368421, 10.        ]])
    

提交回复
热议问题