Suppose we have a matrix that looks as follows:
-0.3 0.2 0.001 -0.4 0.5
0.25 0.45 0.2 -0.001 0.02
0.8 - 0.2 0.35 0.1 0.1
0.25 -0.14 -0.1 0.02 0.4
Now I want to find that part of the matrix which has dimension 2 x 2 AND has the largest elements (in absolute values) in it. So here this would be the following indices:
2 1
2 2
3 1
3 2
because
0.25 0.4
0.8 -0.2
is that part of the matrix which has the largest values of ALL the 2 x 2 matrices in this matrix.
How can I implement this in R?
I've made this little example, because my real matrix contains about 4000 columns and 5000 rows, but many values in this matrix are almost zero. This is difficult to visualize, so for that reason I would like to only visualize the most important ones.
You can use which
to find the indices of the maximum for your matrix.
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
If you are looking for the maximum in each column (or row) you can use:
apply(mat, 2, which.max)
# [1] 4 1 1 1 3
EDIT AFTER QUESTION CLARIFICATION
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