# [R] efficient submatrix extraction

Rajarshi Guha rxg218 at psu.edu
Wed Sep 15 23:10:54 CEST 2004

```Hi,
I have a matrix of say 1024x1024 and I want to look at it in chunks.
That is I'd like to divide into a series of submatrices of order 2x2.

| 1 2 3 4 5 6 7 8 ... |
| 1 2 3 4 5 6 7 8 ... |
| 1 2 3 4 5 6 7 8 ... |
| 1 2 3 4 5 6 7 8 ... |
...

So the first submatrix would be

| 1 2 |
| 1 2 |

the second one would be

| 3 4 |
| 3 4 |

and so on. That is I want the matrix to be evenly divided into 2x2
submatrices. Now I'm also doing this subdivision into 4x4, 8x8 ...
256x256 submatrices.

Currently I'm using loops and I'm sure there is a mroe efficient way to
do it:

m <- matrix(runif(1024*1024), nrow=1024)
boxsize <- 2^(1:8)

for (b in boxsize) {
bcount <- 0
bstart <- seq(1,1024, by=b)
for (x in bstart) {
for (y in bstart) {
xend <- x + b - 1
yend <- y + b - 1
if (length(which( m[ x:xend, y:yend ] > 0.7)) > 0) {
bcount <- bcount + 1
}
}
}
}

Is there any way to vectorize the two inner loops?

Thanks,

-------------------------------------------------------------------
Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
-------------------------------------------------------------------
The way to love anything is to realize that it might be lost.

```