【问题标题】:Extracting all Square Matrices of a Matrix提取矩阵的所有方阵
【发布时间】:2019-01-29 20:53:23
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    以下应该做你想做的事。首先进行一些设置。

    # 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.

    【讨论】:

    • 谢谢安德烈斯,我应该更清楚一点,我不想在提取子矩阵时修改矩阵的结构,例如我只对两个 (3*3) 子矩阵感兴趣来自 S。它们是 I1=matrix(1:9, nrow=3) 和 I2 = matrix(4:12, nrow=3)。很抱歉造成混乱。
    • 太棒了!非常感谢!
    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 2019-08-01
    • 2021-10-14
    • 2017-10-31
    • 2018-02-11
    • 2011-09-05
    相关资源
    最近更新 更多