我有两个身份矩阵,我想以特定的方式合并。例如,如果我有两个矩阵,如:
[i 0] [j 0]
[0 i] and [0 j]
我想在列之间交替挤压它们以获得类似的东西:
[i j 0 0]
[0 0 i j]
无论如何要用numpy这样做?所以使用这样的数据:
size = 2
i = 1.2
j = 1.3
m1 = np.eye(size)*i
m2 = np.eye(size)*j
m1
>>>array([[ 1.2, 0. ],
[ 0. , 1.2]])
m2
>>>array([[ 1.3, 0. ],
[ 0. , 1.3]])
返回类似以下内容的函数:
array([[ 1.2, 1.3, 0. , 0. ],
[ 0. , 0. , 1.2, 1.3]])
答案 0 :(得分:1)
问题是 - " ... squish them together alternating between columns
"。所以,考虑到这个目标,你可以做到 -
np.concatenate((m1,m2)).T.reshape(-1,m1.shape[0]).T
或更短的 -
np.dstack((m1,m2)).reshape(m1.shape[0],-1)
示例运行 -
In [273]: m1
Out[273]:
array([[48, 31, 36, 30, 15],
[27, 14, 14, 13, 30]])
In [274]: m2
Out[274]:
array([[42, 39, 29, 35, 17],
[31, 11, 39, 10, 28]])
In [275]: np.concatenate((m1,m2)).T.reshape(-1,m1.shape[0]).T
Out[275]:
array([[48, 42, 31, 39, 36, 29, 30, 35, 15, 17],
[27, 31, 14, 11, 14, 39, 13, 10, 30, 28]])
In [276]: np.dstack((m1,m2)).reshape(m1.shape[0],-1)
Out[276]:
array([[48, 42, 31, 39, 36, 29, 30, 35, 15, 17],
[27, 31, 14, 11, 14, 39, 13, 10, 30, 28]])
答案 1 :(得分:1)
又一个:
In [315]: out = np.zeros((size,2*size))
In [316]: out[:,0::2]=m1
In [317]: out[:,1::2]=m2
In [318]: out
Out[318]:
array([[ 1.2, 1.3, 0. , 0. ],
[ 0. , 0. , 1.2, 1.3]])
答案 2 :(得分:0)
你可以试试这个:
np.hstack(map(np.transpose,map(np.vstack, zip(m1, m2))))
答案 3 :(得分:0)
针对此特定问题
np.kron(np.eye(2),[m1[0,0],m2[0,0]])
就足够了,您可以根据需要添加第二个参数