python numpy:如何从两个小数组构造一个大对角数组(矩阵)
我想直接从python numpy:如何从两个小数组构造一个大对角数组(矩阵),python,arrays,numpy,Python,Arrays,Numpy,我想直接从A和B生成C,有没有简单的方法来构造对角数组C?谢谢。方法#1:一个简单的方法是- 样本运行- Z = np.zeros((2,2),dtype=int) # Create off-diagonal zeros array out = np.asarray(np.bmat([[A, Z], [Z, B]])) 方法#2:对于一般数量的数组,我们可以使用- 方法#3:对于一般数量的数组,另一种方法是- 样本运行- def diag_block_mat_slicing(L):
A
和B
生成C
,有没有简单的方法来构造对角数组C
?谢谢。方法#1:一个简单的方法是-
样本运行-
Z = np.zeros((2,2),dtype=int) # Create off-diagonal zeros array
out = np.asarray(np.bmat([[A, Z], [Z, B]]))
方法#2:对于一般数量的数组,我们可以使用- 方法#3:对于一般数量的数组,另一种方法是- 样本运行-
def diag_block_mat_slicing(L):
shp = L[0].shape
N = len(L)
r = range(N)
out = np.zeros((N,shp[0],N,shp[1]),dtype=int)
out[r,:,r,:] = L
return out.reshape(np.asarray(shp)*N)
C
是你想要的输出还是什么?是的,C是你想要的输出。你能让它对像A-J这样的10个数组更具编程性吗?@Divakar,是否可以转换回np.array
?现在看起来像是np.matrix
。@ollydbg23为此进行了编辑。@MYGz为这种通用情况添加了一种方法。@Divakar谢谢。
In [24]: Z = np.zeros((2,2),dtype=int)
In [25]: np.asarray(np.bmat([[A, Z], [Z, B]]))
Out[25]:
array([[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 5, 6],
[0, 0, 7, 8]])
def diag_block_mat_boolindex(L):
shp = L[0].shape
mask = np.kron(np.eye(len(L)), np.ones(shp))==1
out = np.zeros(np.asarray(shp)*len(L),dtype=int)
out[mask] = np.concatenate(L).ravel()
return out
def diag_block_mat_slicing(L):
shp = L[0].shape
N = len(L)
r = range(N)
out = np.zeros((N,shp[0],N,shp[1]),dtype=int)
out[r,:,r,:] = L
return out.reshape(np.asarray(shp)*N)
In [137]: A = np.array([[1, 2],
...: [3, 4]])
...: B = np.array([[5, 6],
...: [7, 8]])
...: C = np.array([[11, 12],
...: [13, 14]])
...: D = np.array([[15, 16],
...: [17, 18]])
...:
In [138]: diag_block_mat_boolindex((A,B,C,D))
Out[138]:
array([[ 1, 2, 0, 0, 0, 0, 0, 0],
[ 3, 4, 0, 0, 0, 0, 0, 0],
[ 0, 0, 5, 6, 0, 0, 0, 0],
[ 0, 0, 7, 8, 0, 0, 0, 0],
[ 0, 0, 0, 0, 11, 12, 0, 0],
[ 0, 0, 0, 0, 13, 14, 0, 0],
[ 0, 0, 0, 0, 0, 0, 15, 16],
[ 0, 0, 0, 0, 0, 0, 17, 18]])
In [139]: diag_block_mat_slicing((A,B,C,D))
Out[139]:
array([[ 1, 2, 0, 0, 0, 0, 0, 0],
[ 3, 4, 0, 0, 0, 0, 0, 0],
[ 0, 0, 5, 6, 0, 0, 0, 0],
[ 0, 0, 7, 8, 0, 0, 0, 0],
[ 0, 0, 0, 0, 11, 12, 0, 0],
[ 0, 0, 0, 0, 13, 14, 0, 0],
[ 0, 0, 0, 0, 0, 0, 15, 16],
[ 0, 0, 0, 0, 0, 0, 17, 18]])