[R] fill binary matrices with random 1s

Dennis Murphy djmuser at gmail.com
Tue Nov 29 16:49:22 CET 2011


Hi:

Here's one approach. I assume that your first 1000 matrices have a
single 1 in each matrix, the next set of 1000 have two 1's, ..., and
the last one has 99 1's. (No point in doing all 1's since they're all
constant.) If that's the case, then try the following.

# Each row represents a different 'density' of 1's
# upper triangle of m is 0
m <- matrix(0, 100, 100)
m[lower.tri(m)] <- 1
diag(m) <- 1
m <- m[-100, ]   # remove row of all 1's

######### Functions to operate on a single matrix ############
# Function to permute a vector of 0's and 1's
# and reshape it into a 10 x 10 matrix
randomMatrix <- function(x) matrix(sample(x), 10, 10)

# Generate a 10 x 10 x 1000 array
marray <- function(x) replicate(1000, randomMatrix(x))

# Create a vector of names to which to assign the results
# of simulating from each row of m:
arraynames <- paste('array', 1:99, sep = '')

# apply the marray() function to each row of m and assign
# to the corresponding index of arraynames
for(i in seq_along(arraynames)) assign(arraynames[i], marray(m[i, ]))

HTH,
Dennis


On Tue, Nov 29, 2011 at 4: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
>
> ....
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list