根据值将矩阵分为两个总和相等的矩阵

时间:2019-12-10 14:58:06

标签: python arrays matrix split size

我想将此矩阵拆分为两个矩阵,这样当我将两个拆分的矩阵求和时,就需要获取原始矩阵。

Amp =  array([[1., 1., 0., 0., 0., 0.],
       [0., 1., 1., 0., 0., 0.],
       [0., 1., 0., 0., 1., 0.],
       [0., 0., 1., 0., 1., 0.],
       [0., 0., 1., 1., 0., 0.],
       [0., 0., 0., 1., 1., 0.],
       [0., 0., 0., 1., 0., 1.]]) 

分为:

Al =  array([[1., 0., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0., 0.]]) 

和:

 Ar =  array([[0., 1., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1., 0.],
       [0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 0., 1.]]) 

实际上,不知道如何执行此操作,因为两个值都为'1',并且始终为1(或零)。

预先感谢

1 个答案:

答案 0 :(得分:1)

我认为做到这一点的最佳方法是使用np.where,它可以满足特定条件的单元格的位置:

>>> np.where(Amp==1)
(array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]), array([0, 1, 1, 2, 1, 4, 2, 4, 2, 3, 3, 4, 3, 5]))

由于结果是按行排序的,因此您可以交替填充A1A2

A1 = np.zeros(Amp.shape)
A2 = np.zeros(Amp.shape)
row_index, col_index = np.where(Amp==1)
for ind in range(0, len(row_index), 2):
    A1[row_index[ind], col_index[ind]] = 1
    A2[row_index[ind+1], col_index[ind+1]] = 1

相关问题