您可以使用which
來查找矩陣的最大值的索引。
set.seed(1234)
mat <- matrix(sample(1:20), ncol = 5)
mat
# [,1] [,2] [,3] [,4] [,5]
# [1,] 3 14 8 20 17
# [2,] 12 10 6 15 16
# [3,] 11 1 7 2 19
# [4,] 18 4 5 9 13
which(mat == max(mat), arr.ind = TRUE)
# row col
# [1,] 1 4
如果你是在每列(或行)尋找最大可以使用:
apply(mat, 2, which.max)
# [1] 4 1 1 1 3
編輯時,問題澄清
mrow <- nrow(mat); mcol <- ncol(mat)
subs <- list()
for (i in 1:(nrow(mat) - 1)) {
for (j in 1:(ncol(mat) - 1)) {
x <- c(i, j, i, j + 1, i + 1, j, i + 1, j + 1)
subs[[paste0(i, j)]] <- matrix(x, ncol = 2, byrow = TRUE)
}
}
sums <- sapply(subs, function (x) sum(abs(mat[x])))
win <- subs[[which(sums == max(sums))]]
mat[win[1, 1]:(win[1, 1] + 1), win[1, 2]:(win[1, 2] + 1)]
# [,1] [,2]
# [1,] 20 17
# [2,] 15 16
你的意思是在你想要的輸出中有0.45而不是0.4嗎? – dayne
是的,它想要2×2矩陣的最大和(使用絕對值)的元素。 – Anita
希望下面的幫助。 –