R 提取矩阵的所有平方矩阵

R 提取矩阵的所有平方矩阵,r,matrix,R,Matrix,我试图提取矩阵中所有可能的平方矩阵, 例如,我有一个矩阵: S = matrix(1:12, nrow=3) 我想从S中提取所有可能的平方矩阵,比如下面两个(3*3)矩阵,而不修改矩阵的结构(保持行和列的顺序不变): 谢谢以下内容可以满足您的要求。首先是一些设置 # Your data S <- matrix(1:12, nrow=3) # Set some helpful variables n <- nrow(S) m <- ncol(S) r <- seq_l

我试图提取矩阵中所有可能的平方矩阵, 例如,我有一个矩阵:

S = matrix(1:12, nrow=3)
我想从S中提取所有可能的平方矩阵,比如下面两个(3*3)矩阵,而不修改矩阵的结构(保持行和列的顺序不变):


谢谢

以下内容可以满足您的要求。首先是一些设置

# 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
如图所示,对于每种尺寸,我们都有正确数量的子矩阵

编辑: 如果只需要“直接”存在的子矩阵(行和列应相邻):


res2谢谢Andres,我本应该更清楚地说明,在提取子矩阵时,我不想修改矩阵的结构,例如,我只对S中的两(3*3)个子矩阵感兴趣。它们是I1=矩阵(1:9,nrow=3)和I2=矩阵(4:12,nrow=3)。抱歉搞混了,太棒了!多谢!
# 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
# 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
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