【发布时间】:2017-10-01 05:17:28
【问题描述】:
我需要将矩阵的对角元素设置为 Inf。
一个简单的方法是使用np.fill_diagonal。
np.fill_diagonal(my_matrix, float('inf')
但是fill_diagonal 修改了输入矩阵,而不是返回一个填充了对角线的新矩阵。
这对我不起作用。我需要在不修改原始矩阵的情况下填充对角线。
当然我可以克隆原始矩阵,所以我会一直保留原始矩阵的副本。但是我不太喜欢这个解决方案,因为我会经常更新我的原始矩阵,因此每次我需要对角线为 inf 时我都必须复制它。
是否有与fill_diagonal 相同但不修改输入矩阵的函数?比如:
new_matrix = np.fill_diagonal(original_matrix, float('inf')
为什么我需要这个:
我的矩阵是点之间的距离矩阵,我想在每一步计算两个最近的点。当然这个矩阵的对角线是0(因为一个点到它自己的距离是0)。所以我确保我不采取同一点的解决方案是将对角线设置为 Inf。
但是一旦找到这两个点,我需要计算这两个点与其余点之间距离的平均值,所以我实际上需要对角线为 0 而不是 Inf。
目前我正在做的是:
- 用 Inf 填充对角线
- 找到最近的 2 个点
- 用 0 填充对角线
-
计算这两个点与其余点之间的平均距离。
# fill diagonal with Inf to avoid taking the diagonals np.fill_diagonal(data, float('inf')) # find the minimum distance idx = np.argmin(data) # fill the diagonals back to 0 np.fill_diagonal(data, 0.0) # get the coordinates of the minimum distance row, col = np.unravel_index(idx,data.shape) # compute the new node as the average distance between the two points new_node = np.mean((data[:,row],data[:,col]),0) # replace the first node (row) with the new node data[:,row] = new_node data[row,:] = new_node.T # delete the second node (col) from the matrix data = np.delete(data, col, 0) # delete row data = np.delete(data, col, 1) # delete column
但是我不喜欢将对角线设置为 Inf 然后返回 0 的想法,我宁愿只将一个函数传递给 argmax,它返回对角线填充有 Inf 的数据,而不实际修改矩阵数据。
类似:
idx = np.argmin(return_filled_diagonals(data, float('Inf'))
# here I can operate with data as usual since it has not been modified.
【问题讨论】:
-
我不确定我是否理解正确:您想要一个填充了对角线的新矩阵,但又不想复制,因为您经常更新它?那究竟应该如何工作?你有用例吗?何时何地(任何需要的特殊功能?)您需要填充对角线吗?