具有行和列和约束的随机二进制矩阵 [英] Random binary matrix with row and column sum constraints
问题描述
我的目标是创建:
- 一个随机填充的矩阵,其条目为
0
或1
.在这种情况下,矩阵为4x24
. - 每个
4
行的行总和恰好是6
. - 每个
24
列的列总和恰好是1
- a randomly populated matrix with entries either
0
or1
. In this particular case, the matrix is4x24
. - The row sum of each of the
4
rows is exactly6
. - The column sum of each of the
24
columns is exactly1
调用所需的矩阵M
.
查看M
的另一种方法:
- 完全等于
1
的24
项. - 没有任何列包含一个以上的
1
条目.
- There are exactly
24
entries equal to1
. - No column has more than one
1
entry.
进度:
每行上都有6
个点,并带有1
条目.其余为零,矩阵稀疏.对于4
行,这意味着M可以由存储1
条目的位置的索引矩阵唯一地确定.将此索引矩阵称为indexM
.
There are 6
spots on each row with a 1
entry. The rest are zero, the matrix is sparse. With 4
rows, this means that M can be uniquely determined by a matrix of indices that stores the locations of the 1
entries. Call this matrix of indices indexM
.
我用1:24
的数字填充了indexM
,而没有替换:
I populated indexM
with the numbers 1:24
sampled without replacement:
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 .
For the given seed, the matrix is: https://pastebin.com/8T21MiDv .
如何将indexM
转换为所需的稀疏矩阵?
How do I turn indexM
into the desired sparse matrix?
我在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.
谢谢.
推荐答案
我在
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)
- col索引为
1:24
- row indices are
rep(1:4, 6)
- col indices are
1:24
行索引和列索引之间的匹配是随机的.我们可以...
The match between row and col indices is randomized. We can...
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))
其中任何一个都会返回类似的内容
any of which will return something like
4 x 24 sparse Matrix of class "ngCMatrix"
[1,] . . . . | | . . | . . . | | . | . . . . . . . .
[2,] . | | . . . | . . | . . . . . . . . | . . . | .
[3,] . . . | . . . | . . | | . . . . | . . . | . . .
[4,] | . . . . . . . . . . . . . | . . | . | . | . |
这篇关于具有行和列和约束的随机二进制矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!