Matlab has a built-in function called rand()
which generates random values uniformly between 0 and 1. To generate random values with different probabilities, you can use the rand()
function along with a probability distribution function (pdf) which determines the likelihood of each value being generated.
For example, suppose you want to generate random integers between 1 and 5 with the following probabilities:
To do this, you can use the randsample()
function and specify the weights for each value based on the desired probabilities. Here's an example code:
main.m267 chars9 lines
In this example, the randsample()
function takes four arguments:
outcomes
: the possible values that can be generated (in this case, integers from 1 to 5)100
: the number of random values to generatetrue
: a flag indicating that we want to generate values with replacement (i.e., it's okay to generate the same value multiple times)probabilities
: the weights/probabilities for each value in the outcomes
arrayUsing this code, you will generate an array random_values
containing 100 randomly generated integers based on the specified probabilities.
gistlibby LogSnag