提取矩阵的所有平方矩阵

时间:2019-01-29 20:53:24

标签: r matrix

我正在尝试提取矩阵的所有可能的平方矩阵, 例如,我有这个矩阵:

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

并且我想从S中提取所有可能的平方矩阵,例如以下两个(3 * 3)矩阵,而无需修改矩阵的结构(保持行和列的顺序不变):

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

谢谢

1 个答案:

答案 0 :(得分:2)

以下应做您想做的。首先进行一些设置。

# 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

因此,我们期望有34个正方形子矩阵,其中12个是1x1,18个是2x2,4个是3x3。

接下来,我们遍历所有可能的r平方和所有组合

# 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

灵感来自here.

相关问题