2
votes

I am trying to extract all possible square matrices of a matrix, for example I have this matrix:

S = matrix(1:12, nrow=3)

and I want to extract all possible square matrices from S like the following two (3*3) matrices without modifying the structure of the matrix (keeping the order of rows and columns intact):

I1 = matrix(1:9, nrow=3) 
I2 = matrix(4:12, nrow=3)

Thanks

1

1 Answers

2
votes

The following should do what you want. First some setup.

# Your data
S <- matrix(1:12, nrow=3) 

# Set some helpful variables
n <- nrow(S)
m <- ncol(S)
r <- seq_len(min(n, m)) # Sizes of square submatrices to extract

# Number of sq. submatrices for each r element 
r.combs <- structure(choose(n, r)*choose(m, r), names = r) 
print(r.combs)
# 1  2  3 
#12 18  4   

# Total number of square submatrices
sum(r.combs)
#[1] 34

So we expect 34 square submatrices of which 12 are 1x1, 18 are 2x2, and 4 are 3x3.

Next, we loop over all square matrices possible r and all combinations

# Initialize list to hold lists of matrices for each R
res <- structure(vector("list", length(r)), names = paste0("r", r))

for (R in r) {
  tmp <- list()
  R_n <- combn(n, R, simplify = FALSE) # List all combinations in (n choose R)
  R_m <- combn(m, R, simplify = FALSE) # List all combinations in (m choose R)
  for(i in seq_along(R_n)) {
    for (j in seq_along(R_m)){
      tmp <- c(tmp, list(S[R_n[[i]], R_m[[j]], drop = FALSE]))
    }
  }
  res[[R]] <- tmp
}

# See structure
str(res, max.level = 1)  # See also str(res)
#List of 3
# $ r1:List of 12
# $ r2:List of 18
# $ r3:List of 4

As seen we have the correct number of submatrices for each size.

Edit: If you want only submatrices that are "directly" present (rows and columns should be adjacent):

res2 <- structure(vector("list", length(r)), names = paste0("r", r))
for (R in r) {
  tmp <- list()
  for (i in R:n - R) {
    for (j in R:m - R) {
      tmp <- c(tmp, list(S[i + 1:R, j + 1:R, drop = FALSE]))
    }
  }
  res2[[R]] <- tmp
}

str(res2, max.level = 1)
#List of 3
# $ r1:List of 12
# $ r2:List of 6
# $ r3:List of 2

With strong inspiration form here.