I want to generate a random M x N matrix with zeros and ones with the following special properties:
1) The ones are only in m of the M rows.
2) The ones are only in n of the N columns.
Suppose I am ONLY given that M=10, N=10, m=6 and n=4. One possible random matrix is given by
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 1 0 0 0 1 0 1 0
[2,] 0 0 1 0 0 0 1 0 1 0
[3,] 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 1 0 0 0 1 0 0 0
[6,] 0 1 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 1 0 0 0 0 0 0 0
[9,] 0 0 1 0 0 0 0 0 1 0
[10,] 0 0 0 0 0 0 0 0 0 0
For reproducibility, I've artificially generated the above "random" matrix using
ex <- matrix(0,10,10)
ex[1,3] <- ex[1,7] <- ex[1,9] <- ex[2,3] <- ex[2,7] <-
ex[2,9] <- ex[5,3] <- ex[5,7] <- ex[6,2] <- ex[8,3] <- ex[9,3] <- ex[9,9] <- 1
Note that
sum(rowSums(ex)>0)
[1] 6
sum(colSums(ex)>0)
[1] 4
which match exactly m and n above.
Question I can generate this in a brute force manner, sampling over the rows and columns, but I need to do this over thousands of such matrices (because the m and n will be different each time) and these matrices are large (M=5000 and N=8000, typically). Is there a way to do this efficiently in R?
Aucun commentaire:
Enregistrer un commentaire