根据值将矩阵拆分为两个和相等的矩阵
Split a matrix into two sum equal matrices based on value
我想将这个矩阵拆分成两个矩阵,这样当我对两个拆分后的矩阵求和时,我需要得到我的原始矩阵。
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(或零)。
提前致谢
我认为最好的方法是使用 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]))
由于结果是按行排序的,所以可以交替填写A1
和A2
。
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
我想将这个矩阵拆分成两个矩阵,这样当我对两个拆分后的矩阵求和时,我需要得到我的原始矩阵。
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(或零)。
提前致谢
我认为最好的方法是使用 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]))
由于结果是按行排序的,所以可以交替填写A1
和A2
。
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