GFauxPas
GFauxPas

Reputation: 299

Random binary matrix with row and column sum constraints

My objective is to create:

Call the desired matrix M.

Another way of looking at M:

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.

Upvotes: 3

Views: 1040

Answers (1)

Frank
Frank

Reputation: 66819

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.

The constraints impose that...

  • 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,] | . . . . . . . . . . . . . | . . | . | . | . |

Upvotes: 3

Related Questions