Python 根据值将矩阵拆分为两个和相等的矩阵
我想把这个矩阵分解成两个矩阵,这样当我取两个分解矩阵的和时,我需要得到我的原始矩阵Python 根据值将矩阵拆分为两个和相等的矩阵,python,arrays,matrix,split,size,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.],
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.]])
以及:
实际上,我不知道怎么做,因为这两个值都是“1”,并且总是1(或零)
提前感谢我认为最好的方法是使用
np。其中
提供满足特定条件的单元格位置:
>>> 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
太棒了,这正是我想要做的!:)
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