【问题标题】:How to create an NxM matrix with each column value in range(x,y)?如何使用范围(x,y)中的每一列值创建一个 NxM 矩阵?
【发布时间】:2020-04-26 02:35:24
【问题描述】:

问题: 我想创建一个 5 维 numpy 矩阵,每列的值限制在一个范围内。我在网上找不到任何解决此问题的方法。

我正在尝试生成表单中的规则列表

Rule: (wordIndex, row, col, dh, dv) 

每列的值都在范围内( (0-7), (0,11), (0,11), (-1,1), (-1,1) )。我想生成所有可能的组合。

我可以很容易地使用五个循环来制作矩阵,一个循环

m, n = 12, 12
rules =[]
for wordIndex in range(0, 15):
    for row in range(0,m):
        for col in range(0,n):
            for dh in range(-1,2):
                for dv in range(-1,2):
                    rules.append([wordIndex, row, col, dh, dv])

但是这种方法需要大量的时间来执行此操作,我想知道是否有更好的矢量化方法来使用 numpy 解决这个问题。

我尝试了以下方法,但似乎都不起作用:

rules = np.mgrid[words[0]:words[-1], 0:11, 0:11, -1:1, -1:1]
rules = np.rollaxis(words,0,4)
rules = rules.reshape((len(words)*11*11*3*3, 5))

另一种失败的方法:

values = list(itertools.product(len(wordsGiven()), range(11), range(11), range(-1,1), range(-1,1)))

我也尝试了 np.arange() 但似乎无法弄清楚如何将 if 用于多维数组。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    我认为应该有更好的方法。但以防万一你找不到它,这里有一个基于 hacky 数组的方法:

    shape = (8-0, 12-0, 12-0, 2-(-1), 2-(-1))
    a = np.zeros(shape)
    #create array of indices
    a = np.argwhere(a==0).reshape(*shape, len(shape))
    #correct the ranges that does not start from 0, here 4th and 5th elements (dh and dv) reduced by -1 (starting range). 
    #You can adjust this for any other ranges and elements easily.
    a[:,:,:,:,:,3:5] -= 1
    

    a的前几个元素:

    [[[[[[ 0  0  0 -1 -1]
         [ 0  0  0 -1  0]
         [ 0  0  0 -1  1]]
    
        [[ 0  0  0  0 -1]
         [ 0  0  0  0  0]
         [ 0  0  0  0  1]]
    
        [[ 0  0  0  1 -1]
         [ 0  0  0  1  0]
         [ 0  0  0  1  1]]]
    
    
       [[[ 0  0  1 -1 -1]
         [ 0  0  1 -1  0]
         [ 0  0  1 -1  1]]
    
        [[ 0  0  1  0 -1]
         [ 0  0  1  0  0]
         [ 0  0  1  0  1]]
    
        [[ 0  0  1  1 -1]
         [ 0  0  1  1  0]
         [ 0  0  1  1  1]]]
    
    
       [[[ 0  0  2 -1 -1]
         [ 0  0  2 -1  0]
         [ 0  0  2 -1  1]]
    
        [[ 0  0  2  0 -1]
         [ 0  0  2  0  0]
         [ 0  0  2  0  1]]
    
        [[ 0  0  2  1 -1]
         [ 0  0  2  1  0]
         [ 0  0  2  1  1]]]
    
    
       ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多