Skip to content
Prev 278774 / 398502 Next

fill binary matrices with random 1s

I have to admit I'm not entirely sure what your question is. How to
put a 1 in a random position in a matrix?

mat <- matrix(0, 10, 10)
 mat[sample(1:nrow(mat), 1), sample(1:ncol(mat), 1)] <- 1
will do so, but if you need to fill a random position that is *currently zero*
then you'll need to wrap it in a while loop and check the value of that cell.

Or, more elegantly, create a random vector of positions in advance,
then fill each:
tofill <- sample(1:100)
for(i in 1:length(tofill)) {
mat[tofill[i]] <- 1
}

But if you don't need sequential matrices, just random matrices of
particular densities, there are nicer ways to create them.

matdensity <- 45
matsize <- 10
mat45 <- matrix(sample(c(rep(1, matdensity), rep(0, matsize*2 -
matdensity))), matsize, matsize)


On Tue, Nov 29, 2011 at 7:32 AM, Grant McDonald
<grantforaccount at hotmail.co.uk> wrote: