Random binary matrix with row and column sum constraints

Viewed 875

My objective is to create:

  • 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

Call the desired matrix M.

Another way of looking at M:

  • There are exactly 24 entries equal to 1.
  • No column has more than one 1 entry.

Progress:

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.

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)

For the given seed, the matrix is: https://pastebin.com/8T21MiDv .

How do I turn indexM into the desired sparse matrix?

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.

Thank you.

1 Answers
Related