# [R] Help with applying a function to all possible 2x2 submatrices

Sarah Goslee sarah.goslee at gmail.com
Mon Oct 22 21:50:26 CEST 2012

```300x300 isn't terribly large; looping should work just fine. But I'm
I would have thought that a submatrix would be adjacent elements, like
x[1:2, 1:2]
or
x[13:14, 296:297]
but your loop compares all possible sets of four elements, so the
matrix position doesn't matter except for avoiding duplication.

Maybe a bit more about what you're trying to accomplish (including the
function you want to perform with those four elements) would be

Sarah

On Mon, Oct 22, 2012 at 1:10 PM, CMB123 <craig.bielski at gmail.com> wrote:
> Hi all,
>
> I'm working with a large data set (on the order of 300X300) and trying to
> apply a function which compares the elements of all possible 2x2
> submatrices. There are rc(r-1)(c-1) such submatrices, so obviously the naive
> method of looping through the rows and columns is computationally unfeasible
> for my data set:
>
>   for(i in 1:(nrow(data)-1)) {
>     for(j in (i+1):nrow(data)) {
>       for (m in 1:(ncol(data)-1)) {
>         for (n in (m+1):ncol(data)) {
>
> I have tried using the outer and apply functions to vectorize the task, but
> I can't seem to figure out the best method (or any method, for that matter)
> to help with what I'm trying to do.
>
> Any and all help is much appreciated! Thanks in advance,
>
> C
>
>

--
Sarah Goslee
http://www.functionaldiversity.org

```