Numpy meshgrid in 3D

前端 未结 7 1204
暖寄归人
暖寄归人 2020-11-27 15:45

Numpy\'s meshgrid is very useful for converting two vectors to a coordinate grid. What is the easiest way to extend this to three dimensions? So given three vectors x, y, an

7条回答
  •  长情又很酷
    2020-11-27 16:20

    Can you show us how you are using np.meshgrid? There is a very good chance that you really don't need meshgrid because numpy broadcasting can do the same thing without generating a repetitive array.

    For example,

    import numpy as np
    
    x=np.arange(2)
    y=np.arange(3)
    [X,Y] = np.meshgrid(x,y)
    S=X+Y
    
    print(S.shape)
    # (3, 2)
    # Note that meshgrid associates y with the 0-axis, and x with the 1-axis.
    
    print(S)
    # [[0 1]
    #  [1 2]
    #  [2 3]]
    
    s=np.empty((3,2))
    print(s.shape)
    # (3, 2)
    
    # x.shape is (2,).
    # y.shape is (3,).
    # x's shape is broadcasted to (3,2)
    # y varies along the 0-axis, so to get its shape broadcasted, we first upgrade it to
    # have shape (3,1), using np.newaxis. Arrays of shape (3,1) can be broadcasted to
    # arrays of shape (3,2).
    s=x+y[:,np.newaxis]
    print(s)
    # [[0 1]
    #  [1 2]
    #  [2 3]]
    

    The point is that S=X+Y can and should be replaced by s=x+y[:,np.newaxis] because the latter does not require (possibly large) repetitive arrays to be formed. It also generalizes to higher dimensions (more axes) easily. You just add np.newaxis where needed to effect broadcasting as necessary.

    See http://www.scipy.org/EricsBroadcastingDoc for more on numpy broadcasting.

提交回复
热议问题