【问题标题】:How to find the indices of the minimum value in a matrix, where row index is not equal to column index?如何在矩阵中找到最小值的索引,其中行索引不等于列索引?
【发布时间】:2023-03-03 19:46:01
【问题描述】:

我在 R 中有一个距离矩阵。我想找到矩阵中最小值的行和列索引,其中行索引不等于列索引(所以不是一个值到自身的距离)。我如何在 R 中做到这一点?

现在我有:

which(D == min(D), arr.ind = TRUE) 

这将返回矩阵中最小值的索引,但不会排除值与它们自身的距离。

【问题讨论】:

  • 问题与machine-learning 无关 - 请不要向标签发送垃圾邮件(已删除)。

标签: r matrix


【解决方案1】:

假设 D 是对称的,并且它的元素是有限的,首先将对角线和上(或下)三角形部分设置为 Inf。 (如果它不是对称的,只需将对角线部分设置为 Inf:diag(D) <- Inf。)

# test input
D <- matrix(1:25, 5)
D <- (D + t(D)) / 2
diag(D) <- 0

D[upper.tri(D, diag = TRUE)] <- Inf
which(D == min(D), arr = TRUE)

给予:

     row col
[1,]   2   1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多