Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

python - Vectorized NumPy linspace across multi-dimensional arrays

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 applying linspace to max and min value. Is there some "numpy"/vectorized way to do this? Example non-vectorized code is below to show results I would like.

import numpy as np

mins = np.random.rand(2,2)
maxs = np.random.rand(2,2)

# Number of elements in the linspace
x = 3

m, n = mins.shape
results = np.zeros((m, n, x))

for i in range(m):
    for j in range(n):
        min = mins[i][j]
        max = maxs[i][j]
        results[i][j] = np.linspace(min, max, num=x)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. ]]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...