2

I'm looking for a way to generate a series of matrices where all the column sums are equal to a specific value. I thought I could generate random matrices and check each one to filter out where colSums= value needed, but that doesn't seem to work. Also, how do we generate random matrices in R with both positive and negative values?

priya12
  • 31
  • 1

1 Answers1

2

You can do like this. This is a function that creates a matrix filled with random numbers from a normal distribution. Then it centers all columns to 0 and adds up the desired number.

RandomMatrixColsum = function(mycolsum=1, dim=c(10, 10), ...){
  m  <- matrix(rnorm(prod(dim), ...), ncol=dim[2])
  ms <- scale(m, center=T, scale=F) + mycolsum/dim[1]
  return(ms)
}
RandomMatrixColsum(8)

If you want to make sure to have both positive and negative values in your matrix, you can increase the standard deviation of the rnorm by adding an argument sd=... to the function call, or also force the sd to be equal to the mean.

agenis
  • 8,069
  • 5
  • 53
  • 102