[R] efficient submatrix extraction

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Thu Sep 16 10:56:38 CEST 2004

```there are two main ideas to improve the efficiency:

1. the comparison with the limit can be done at first
2. a matrix with boxsize*boxsize rows can be defined so that
you can apply function "apply" without using inner loops

<<*>>=
# parameters
size<-1024; limit<-0.7
# some data
set.seed(17); data<-runif(size^2)
m<-matrix(data,size,size)
bcount.vec<-NULL
m<-m>limit
for (boxsize in 2^(1:8)) {
# inner loop:
m<-array(m,c(boxsize,size/boxsize,size))
m<-aperm(m,c(1,3,2))
m<-matrix(m,nrow=boxsize*boxsize)
bcount.vec<-c(bcount.vec,sum(apply(m,2,max)))
}
bcount<-sum(bcount.vec)
print(bcount.vec)
print(bcount)

@
output-start
[1] 199099  65306  16384   4096   1024    256     64     16
[1] 286245
output-end

Some remarks on your code:
The first expression in your outer loop is setting bcount to 0.
In the inner loops bcount is incremented.
But the outer loop sets bcount to the value 0 again!?
What do you want to count?

Peter

Rajarshi Guha wrote:

>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.
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
>

```