[R] fill binary matrices with random 1s

Sarah Goslee sarah.goslee at gmail.com
Tue Nov 29 15:24:47 CET 2011

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:
> Dear all, I am finding difficulty in the following, I would like to
> create an empty matrix e.g. 10x10 of 0s and sequentially fill this
> matrix with randomly placed a 1s until it is saturated. Producing 100
> matrices of sequentially increasing density., This process needs to be
> randomized 1000 times., I assume i should run this along the following
> lines, 1) Create 1000 matrices all zeros, 2) add a random 1 to all
> matrices, 3) run function on all 1000 matrices and output results to a
> vector table (i.e. calculate density of matric at each step for all 100 matrices.
> )., 4) add another 1 to the previous 1000 matrices in a
> random position., repeat till all matrices saturated., I have looked
> through histories on random fill algorithms but all packages I can find
> nothing as simple as the random fill I am looking for., sorry for
> bothering, Thank you for any help in advance.
> Something that starts along the lines of the following? Sorry this example is atrocious.
> matrixfill <- function(emptymatrix, K=fullmatrix, time=100, from=0, to=time)
> {
> N <- numeric(time+1)
> N[1] <- emptymatrix
> for (i in 1:time) N[i+1] <- N[i]+"place random 1 in a random xy position" until K.
> Calculate Density of matrix

Sarah Goslee

More information about the R-help mailing list