具有行和列和约束的随机二进制矩阵 [英] Random binary matrix with row and column sum constraints

查看:91
本文介绍了具有行和列和约束的随机二进制矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是创建:

  • 一个随机填充的矩阵,其条目为01.在这种情况下,矩阵为4x24.
  • 每个4行的行总和恰好是6.
  • 每个24列的列总和恰好是1
  • a randomly populated matrix with entries either 0 or 1. In this particular case, the matrix is 4x24.
  • The row sum of each of the 4 rows is exactly 6.
  • The column sum of each of the 24 columns is exactly 1

调用所需的矩阵M.

查看M的另一种方法:

  • 完全等于124项.
  • 没有任何列包含一个以上的1条目.
  • There are exactly 24 entries equal to 1.
  • 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 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)
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆