为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容3067478 2022-10-05 17:52:48
我对矩阵加法有疑问。我有一个矩阵 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 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

这是一种方法:


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


查看完整回答
反对 回复 2022-10-05
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信