How to create a matrix with probability distribution in R

2.2k views Asked by At

I want to create a matrix in R with element [-1,0,1] with probability [1/6, 2/3, 1/6] respectively. The probability may change during runtime. for static probability I have got the output but the problem is dynamic change in the probability. for example, If I create a matrix for the above probability with [sqrt(3),0,-sqrt(3)], the required output is.

Note: The Probability should not be static as mentioned. It may vary during runtime.

Kindly help to solve this.

enter image description here

2

There are 2 answers

3
mpjdem On BEST ANSWER

Supposing you want a 2x3 matrix:

matrix(sample(c(-1,0,1), size=6, replace=TRUE, prob=c(1/6,2/3,1/6)), nrow=2)

So you sample from the values you want, with probabilities defined in prob. This is just a vector, but you can make it into a matrix of the desired shape using matrix afterwards. Replace the probabilities by a variable instead of values to not make it static.

If the numbers should be distributed according to a certain scheme rather than randomly drawn according to a probability, replicate the vector elements and shuffle them:

 matrix(sample(rep(c(-1,0,1), times=c(1,4,1))), nrow=2)
1
Sandipan Dey On

You can try this to generate a mxn matrix:

sample.dynamic.matrix <- function(pop.symbols, probs, m, n) {
   samples <- sample(pop.symbols, m*n, prob = probs, replace=TRUE)
   return(matrix(samples, nrow=m))
}

set.seed(123)
sample.dynamic.matrix(-1:1, c(1/6,2/3,1/6), 2, 3)
#     [,1] [,2] [,3]
#[1,]    0    0   -1
#[2,]    1   -1    0