将矩阵插入另一个矩阵(特定位置)

时间:2020-04-10 20:12:18

标签: python matrix

我对矩阵加法有疑问。我有一个矩阵A = np.ones([10,10])和一个矩阵B = np.array([[2,2,2],[2,2,2],[2,2,2]] )。现在,我想将矩阵B添加到A中,但在特定位置,第2、6、7行和第2、6、7列。

我应该如何获取以下矩阵:

[[1,1,1,1,1,1,1,1,1,1],
 [1,1,1,1,1,1,1,1,1,1],
 [1,1,3,1,1,1,3,3,1,1],
 [1,1,1,1,1,1,1,1,1,1],
 [1,1,1,1,1,1,1,1,1,1],
 [1,1,1,1,1,1,1,1,1,1],
 [1,1,3,1,1,1,3,3,1,1],
 [1,1,3,1,1,1,3,3,1,1],
 [1,1,1,1,1,1,1,1,1,1],
 [1,1,1,1,1,1,1,1,1,1]]

我更习惯于Matlab,那里看起来像这样:A((3,7,8),(3,7,8))= A((3,7,8),( 3,7,8))+B。我在Python中尝试了类似的操作,但尺寸不匹配。

1 个答案:

答案 0 :(得分:1)

这是一种实现方法:

Python中的多维索引要求您显式索引每个单元格。因此,您需要首先创建索引,然后按如下所示使用它:

ind = np.array([[2,6,7]])   # Notice the 2D array
rows = np.broadcast_to(ind.transpose(), (3,3))
cols = np.broadcast_to(ind, (3,3))
A[rows, cols]+=B  # A cell from rows matrix and a corresponding cell in cols matrix together form one cell index.

输出:

array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
   [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
   [1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
   [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
   [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
   [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
   [1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
   [1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
   [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
   [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

请阅读:https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html

由于某些原因,尽管以下内容确实从A中选择了正确的矩阵,但对其的分配不起作用:

ind_1 = np.array([2,6,7])
A[ind_1,:][:, ind_1] = B # No error, but assignment does not take place