【问题标题】:Split a matrix into two sum equal matrices based on value根据值将矩阵拆分为两个总和相等的矩阵
【发布时间】:2019-12-10 14:58:06
【问题描述】:

我想将此矩阵拆分为两个矩阵,这样当我将两个拆分后的矩阵相加时,我需要得到我的原始矩阵。

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(或零)。

提前致谢

【问题讨论】:

    标签: python arrays matrix split size


    【解决方案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
    
    

    【讨论】:

    • 太棒了,这正是我想做的! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2021-08-17
    • 2020-12-29
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多