簡體   English   中英

如何使用范圍(x,y)中的每一列值創建一個 NxM 矩陣?

[英]How to create an NxM matrix with each column value in range(x,y)?

問題:我想創建一個 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 用於多維數組。

我認為應該有更好的方法。 但以防萬一你找不到它,這里有一個基於 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]]]


   ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM