# [R] fill binary matrices with random 1s

David Winsemius dwinsemius at comcast.net
Tue Nov 29 15:57:00 CET 2011

```On Nov 29, 2011, at 7:32 AM, Grant McDonald 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

Ewww. That looks painful. Consider this as an alternative to create a
single such "random matrix":

rmat <- matrix(rbinom(100, 1, prob=0.1), 10,10)

> rmat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    0    0    0    0    0    1     0
[2,]    1    0    0    0    0    0    0    0    0     0
[3,]    0    0    0    0    1    0    0    0    0     0
[4,]    1    0    0    0    0    0    0    0    0     0
[5,]    0    0    0    1    1    0    0    0    0     0
[6,]    0    0    0    0    0    0    1    0    0     0
[7,]    0    0    0    0    0    0    0    0    1     0
[8,]    0    1    0    0    0    0    0    0    0     0
[9,]    0    0    0    0    0    0    0    0    1     0
[10,]    0    0    0    0    0    1    0    0    0     0

--

David Winsemius, MD
West Hartford, CT

```