Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 用不定方程的正整数解生成矩阵_R - Fatal编程技术网

R 用不定方程的正整数解生成矩阵

R 用不定方程的正整数解生成矩阵,r,R,我以前问过一个类似的问题。但是这个有点棘手。对于不定方程x1+x2+x3=8,我有正整数解(以前是非负解)矩阵(比如A)。另外,我还有另一个矩阵(比如B)和列 0 1 0 1 0 0 1 1 我想使用A行和B列生成矩阵 例如,假设(2,2,4)是矩阵A的一个解决方案(一行)。在这种情况下,我无法使用rep。因此,我尝试从矩阵B生成所有三列矩阵,然后尝试应用rep,但无法解决这个问题。我使用以下几行生成所有三列矩阵的列表 cols <- combn(ncol(B), 3, simplify

我以前问过一个类似的问题。但是这个有点棘手。对于不定方程
x1+x2+x3=8
,我有正整数解(以前是非负解)矩阵(比如
A
)。另外,我还有另一个矩阵(比如
B
)和列

0 1 0 1
0 0 1 1
我想使用
A
行和
B
列生成矩阵

例如,假设
(2,2,4)
是矩阵
A
的一个解决方案(一行)。在这种情况下,我无法使用
rep
。因此,我尝试从矩阵
B
生成所有三列矩阵,然后尝试应用
rep
,但无法解决这个问题。我使用以下几行生成所有三列矩阵的列表

cols <- combn(ncol(B), 3, simplify=F, FUN=as.numeric)
M3 <- lapply(cols, function(x) cbind(B[,x]))
这个新矩阵的列是B列的倍数,即第一列2倍,第二列2倍,第三列4倍。我想在矩阵A的所有行中使用此过程。我如何做到这一点?

?rep(x,times)

如果时间是与x长度相同的向量(通过复制后 每个),结果由x[1]次重复[1]次,x[2]次组成 重复[2]次,以此类推

基本思想是

B <- matrix(c(0, 1, 0, 1, 0, 0, 1, 1), byrow = T, nrow = 2)
cols <- combn(ncol(B), 3, simplify=F, FUN=as.numeric)

a1 <- c(2, 2, 4)    
cols[[1]]  # [1] 1 2 3
rep(cols[[1]], a1)   # [1] 1 1 2 2 3 3 3 3

B[, rep(cols[[1]], a1)]
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,]    0    0    1    1    0    0    0    0
# [2,]    0    0    0    0    1    1    1    1
B
?rep(x,times)

如果时间是与x长度相同的向量(通过复制后 每个),结果由x[1]次重复[1]次,x[2]次组成 重复[2]次,以此类推

基本思想是

B <- matrix(c(0, 1, 0, 1, 0, 0, 1, 1), byrow = T, nrow = 2)
cols <- combn(ncol(B), 3, simplify=F, FUN=as.numeric)

a1 <- c(2, 2, 4)    
cols[[1]]  # [1] 1 2 3
rep(cols[[1]], a1)   # [1] 1 1 2 2 3 3 3 3

B[, rep(cols[[1]], a1)]
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,]    0    0    1    1    0    0    0    0
# [2,]    0    0    0    0    1    1    1    1
B
testA <- rbind(c(2,2,4), c(2,1,5), c(2,3,3))

 ## apply(..., lapply(...)) approach (output is list in list)
apply(testA, 1, function(x) lapply(cols, function(y) B[, rep(y, x)]))

 ## other approach using combination of indices
ind <- expand.grid(ind_cols = 1:length(cols), ind_A = 1:nrow(testA))
col_ind <- apply(ind, 1, function(x) rep(cols[[x[1]]], testA[x[2],]))

lapply(1:ncol(col_ind), function(x) B[, col_ind[,x]])   # output is list

library(dplyr)
apply(col_ind, 2, function(x) t(B[, x])) %>% matrix(ncol = 8, byrow=T)  # output is matrix