Vectorized NumPy linspace across multi-dimensional arrays

后端 未结 2 1839
栀梦
栀梦 2020-12-11 18:11

Say I have 2 numpy 2D arrays, mins, and maxs, that will always be the same dimension as one another. I\'d like to create a third array, results, that is the result of apply

2条回答
  •  Happy的楠姐
    2020-12-11 18:52

    Here's one vectorized approach based on this post to cover for generic n-dim cases -

    def create_ranges_nd(start, stop, N, endpoint=True):
        if endpoint==1:
            divisor = N-1
        else:
            divisor = N
        steps = (1.0/divisor) * (stop - start)
        return start[...,None] + steps[...,None]*np.arange(N)
    

    Sample run -

    In [536]: mins = np.array([[3,5],[2,4]])
    
    In [537]: maxs = np.array([[13,16],[11,12]])
    
    In [538]: create_ranges_nd(mins, maxs, 6)
    Out[538]: 
    array([[[  3. ,   5. ,   7. ,   9. ,  11. ,  13. ],
            [  5. ,   7.2,   9.4,  11.6,  13.8,  16. ]],
    
           [[  2. ,   3.8,   5.6,   7.4,   9.2,  11. ],
            [  4. ,   5.6,   7.2,   8.8,  10.4,  12. ]]])
    

提交回复
热议问题