Skip to content
Prev 278785 / 398502 Next

fill binary matrices with random 1s

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: