如何从矩阵中选择特定的非对角带?

时间:2018-12-31 02:48:59

标签: python numpy

假设一个NxN方阵。我想选择一个宽度w与主对角线偏移k的波段,如以下N = 9, w = 4, k = -1的示例所示

enter image description here

元素的顺序应与np.tril_indices(N, k=k)相同。因此,基本上相应的索引应该np.tril_indices(N, k=k)减少np.tril_indices(N, k=k-w)

i1 = list(zip(*np.tril_indices(N, k=k)))
i2 = list(zip(*np.tril_indices(N, k=k-w)))
indices = tuple(zip(*[i for i in i1 if i not in i2]))
M[indices]

或者使用np.tril来存储整个矩阵作为中间结果,并且仅适用于2D数组:

B = np.ravel(np.tril(M, k=k) - np.tril(M, k=k-w))
B[B.nonzero()]

我想知道是否有更有效和/或更简洁的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

In [19]: np.tri(6,6, dtype=bool)
Out[19]: 
array([[ True, False, False, False, False, False],
       [ True,  True, False, False, False, False],
       [ True,  True,  True, False, False, False],
       [ True,  True,  True,  True, False, False],
       [ True,  True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True,  True]])

结合2个tri面具:

In [22]: np.tri(6,6, dtype=bool)&~np.tri(6,6,-3,dtype=bool)
Out[22]: 
array([[ True, False, False, False, False, False],
       [ True,  True, False, False, False, False],
       [ True,  True,  True, False, False, False],
       [False,  True,  True,  True, False, False],
       [False, False,  True,  True,  True, False],
       [False, False, False,  True,  True,  True]])

In [23]: np.where(Out[22])
Out[23]: 
(array([0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5]),
 array([0, 0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5]))

np.tri本质上是:

In [29]: np.greater_equal.outer(np.arange(4),np.arange(4))
Out[29]: 
array([[ True, False, False, False],
       [ True,  True, False, False],
       [ True,  True,  True, False],
       [ True,  True,  True,  True]])
In [30]: np.greater_equal(np.arange(4)[:,None],np.arange(4))
Out[30]: 
array([[ True, False, False, False],
       [ True,  True, False, False],
       [ True,  True,  True, False],
       [ True,  True,  True,  True]])

np.tril仅对此应用where

In [37]: np.greater_equal(np.arange(4)[:,None], np.arange(4)) & 
         np.less_equal(np.arange(-1,3)[:,None], np.arange(4))
Out[37]: 
array([[ True, False, False, False],
       [ True,  True, False, False],
       [False,  True,  True, False],
       [False, False,  True,  True]])