Cla*_*ist 6 r permutation matrix
考虑以下简化示例,其中所有可能的 2 x 2 矩阵均包含一个 1 和其余 0。
library(arrangements)
# define function
generate_matrices <- function(nrow, ncol, ones_count) {
vectors <- permutations(c(
rep(1, ones_count),
rep(0, nrow * ncol - ones_count)
))
# remove redundancies
vectors <- vectors[!duplicated(vectors),]
# list of matrices
out <- list()
for (i in 1:ncol(vectors)) {
out[[i]] <- matrix(
data = vectors[,i],
nrow = nrow,
ncol = ncol,
byrow = TRUE
)
}
return(out)
}
Run Code Online (Sandbox Code Playgroud)
运行函数生成所有带有一个 1 的 2 x 2 矩阵:
generate_matrices(nrow = 2, ncol = 2, ones_count = 1)
[[1]]
[,1] [,2]
[1,] 1 0
[2,] 0 0
[[2]]
[,1] [,2]
[1,] 0 1
[2,] 0 0
[[3]]
[,1] [,2]
[1,] 0 0
[2,] 1 0
[[4]]
[,1] [,2]
[1,] 0 0
[2,] 0 1
Run Code Online (Sandbox Code Playgroud)
当我将其扩展到具有 5 行、4 列和 4 个的矩阵时,会出现错误:
generate_matrices(nrow = 5, ncol = 4, ones_count = 4)
# Error in permutations(c(rep(1, ones_count), rep(0, nrow * ncol - ones_count))) :
# too many results
Run Code Online (Sandbox Code Playgroud)
我的猜测是这些行
vectors <- permutations(c(
rep(1, ones_count),
rep(0, nrow * ncol - ones_count)
))
Run Code Online (Sandbox Code Playgroud)
运行时间太长和/或我的笔记本电脑上没有足够的内存来存储这些。有没有更有效的方法来实现这一点?
值得注意的是,我想最终将其扩展到 6 x 5 的情况(有 4 个)和 8 x 5 的情况(有 8 个)。
您可以采用 1 的索引组合:
m <- 2
n <- 2
k <- 2
createMatrix <- function(m, n, indices){
x <- matrix(0, m, n)
x[indices] <- 1
x
}
lapply(
combn(seq_len(m*n), k, simplify = FALSE),
function(x) createMatrix(m, n, x)
)
Run Code Online (Sandbox Code Playgroud)
其中m
是行数、n
列数和k
个数。