跨多维数组的矢量化NumPy Linspace [英] Vectorized NumPy linspace across multi-dimensional arrays

查看:99
本文介绍了跨多维数组的矢量化NumPy Linspace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有2个numpy 2D数组,最小值和最大值,它们总是彼此相同的尺寸.我想创建第三个数组,结果,这是将linspace应用于最大值和最小值的结果.是否有某种"numpy"/矢量化方法可以做到这一点?下面是示例非矢量化代码,以显示我想要的结果.

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)

推荐答案

这里是一种基于 this post 的矢量化方法普通n-dim案件的保险范围-

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)

样品运行-

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

这篇关于跨多维数组的矢量化NumPy Linspace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆