0

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

0

2 Answers 2

3

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @mpjdem, but the output gives 3 zeros, 2 (-1) and 1 (+1). I need 4 zeros according to condition
It's a probability, so it's not deterministic. For what you want, you would need the rep function with the times argument, and then use sampleon it to shuffle it. I'll quickly write it up.
Yeah I understand, Thank you
1

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 

1 Comment

Thank you @sandipan for the elaborate answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.