[英]Extracting all Square Matrices of a Matrix
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):并且我想从 S 中提取所有可能的方阵,例如以下两个(3 * 3)矩阵,而不修改矩阵的结构(保持行和列的顺序不变):
I1 = matrix(1:9, nrow=3)
I2 = matrix(4:12, nrow=3)
Thanks谢谢
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.所以我们期望 34 个方形子矩阵,其中 12 个是 1x1,18 个是 2x2,4 个是 3x3。
Next, we loop over all square matrices possible r
and all combinations接下来,我们遍历所有可能的方阵
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.