具有行和列总和约束的随机二进制矩阵
Random binary matrix with row and column sum constraints
我的objective是创建:
- 一个随机填充的矩阵,其条目为
0
或 1
。在这种特殊情况下,矩阵是 4x24
.
- 每
4
行的行总和正好是 6
.
- 每个
24
列的列总和正好是 1
调用所需的矩阵M
。
另一种看待M
的方式:
- 恰好有
24
个条目等于 1
。
- 没有一列有超过一个
1
条目。
进度:
每行有 6
个点,有 1
个条目。其余为零,矩阵稀疏。对于 4
行,这意味着 M 可以由存储 locations of [=12] 的 indices 矩阵唯一确定=]条目。调用这个索引矩阵 indexM
.
我在 indexM
中填充了 1:24
采样的数字,无需替换:
set.seed(30592)
colNum <- 24
rowSum <-6
numZeros <- colNum-rowSum
OneRow<-c(rep(1,rowSum),rep(0,numZeros))
indexM<-matrix(sample(1:24,replace=FALSE),
nrow=4,ncol=6,byrow=TRUE)
对于给定的种子,矩阵是:https://pastebin.com/8T21MiDv .
如何将 indexM
转换为所需的稀疏矩阵?
我在 Matrix
库中找到了 sparseMatrix
,但它需要一个向量或行索引以及另一个列索引向量,而我没有。
谢谢。
I found the sparseMatrix
in the Matrix
library, but it wants a vector or row indices and another vector of column indices, which is not what I have.
约束强加于...
- 行索引是
rep(1:4, 6)
- 列索引为
1:24
行索引和列索引之间的匹配是随机的。我们可以...
library(Matrix)
# fix rows, jumble cols
sparseMatrix(rep(1:4, each=6), sample(1:24))
# fix cols, jumble rows
sparseMatrix(sample(rep(1:4, each=6)), 1:24)
# jumbl'm all
sparseMatrix(sample(rep(1:4, each=6)), sample(1:24))
其中任何一个都会 return 类似于
4 x 24 sparse Matrix of class "ngCMatrix"
[1,] . . . . | | . . | . . . | | . | . . . . . . . .
[2,] . | | . . . | . . | . . . . . . . . | . . . | .
[3,] . . . | . . . | . . | | . . . . | . . . | . . .
[4,] | . . . . . . . . . . . . . | . . | . | . | . |
我的objective是创建:
- 一个随机填充的矩阵,其条目为
0
或1
。在这种特殊情况下,矩阵是4x24
. - 每
4
行的行总和正好是6
. - 每个
24
列的列总和正好是1
调用所需的矩阵M
。
另一种看待M
的方式:
- 恰好有
24
个条目等于1
。 - 没有一列有超过一个
1
条目。
进度:
每行有 6
个点,有 1
个条目。其余为零,矩阵稀疏。对于 4
行,这意味着 M 可以由存储 locations of [=12] 的 indices 矩阵唯一确定=]条目。调用这个索引矩阵 indexM
.
我在 indexM
中填充了 1:24
采样的数字,无需替换:
set.seed(30592)
colNum <- 24
rowSum <-6
numZeros <- colNum-rowSum
OneRow<-c(rep(1,rowSum),rep(0,numZeros))
indexM<-matrix(sample(1:24,replace=FALSE),
nrow=4,ncol=6,byrow=TRUE)
对于给定的种子,矩阵是:https://pastebin.com/8T21MiDv .
如何将 indexM
转换为所需的稀疏矩阵?
我在 Matrix
库中找到了 sparseMatrix
,但它需要一个向量或行索引以及另一个列索引向量,而我没有。
谢谢。
I found the
sparseMatrix
in theMatrix
library, but it wants a vector or row indices and another vector of column indices, which is not what I have.
约束强加于...
- 行索引是
rep(1:4, 6)
- 列索引为
1:24
行索引和列索引之间的匹配是随机的。我们可以...
library(Matrix)
# fix rows, jumble cols
sparseMatrix(rep(1:4, each=6), sample(1:24))
# fix cols, jumble rows
sparseMatrix(sample(rep(1:4, each=6)), 1:24)
# jumbl'm all
sparseMatrix(sample(rep(1:4, each=6)), sample(1:24))
其中任何一个都会 return 类似于
4 x 24 sparse Matrix of class "ngCMatrix"
[1,] . . . . | | . . | . . . | | . | . . . . . . . .
[2,] . | | . . . | . . | . . . . . . . . | . . . | .
[3,] . . . | . . . | . . | | . . . . | . . . | . . .
[4,] | . . . . . . . . . . . . . | . . | . | . | . |