Skip to content
Prev 308695 / 398503 Next

Help with applying a function to all possible 2x2 submatrices

Hello,

If your matrix is in the order of 300x300, the problem of extracting all 
possible submatrices and applying a function will allways be a large 
one, but the use of ?combn may reduce it a bit if the order of 
rows/columns in the submatrices doesn't matter. It can reduce it from 
300^4 = 8.1e+09 to 2.0e+09 submatrices, a factor of 4.
See the example below.

# Make up some data.
nr <- nc <- 10
x <- matrix(rnorm(nr*nc), nrow = nr)

cr <- combn(nr, 2)
cc <- combn(nc, 2)

fun <- function(rr, cc, xx, FUN) FUN(xx[rr, cc])

apply(cr, 2, function(i)
     apply(cc, 2, function(j)
         fun(cr[, i], cc[, j], x, sum)
     )
)


Note that this hides away the quartic nature of the algorithm.

Hope this helps,

Rui Barradas
Em 22-10-2012 18:10, CMB123 escreveu: