Contents
seed random number generator to state zero (debugging and development)
utility function: seedRNG0.m
if verLessThan('matlab', '8.0.0')
RandStream.setDefaultStream(RandStream('mt19937ar','seed',0));
else
RandStream.setGlobalStream(RandStream('mt19937ar','seed',0));
end
seed random number generator using system date/time (simulation)
utility function: seedRNG.m
if verLessThan('matlab', '8.0.0')
RandStream.setDefaultStream(RandStream('mt19937ar','seed',sum(clock*100)));
else
RandStream.setGlobalStream(RandStream('mt19937ar','seed',sum(clock*100)));
end
draw N samples from rectangular distribution ranging from 0.0 - 1.0
N=5; sample = rand(N,1)
sample =
0.6685
0.8842
0.4474
0.9790
0.5871
generate N values drawn from uniform distribution in the range of [a, b]
N=10; a=1; b=10;
sample = a + (b-a) .* rand(N,1)
sample = floor(sample + 0.5)
sample =
6.0448
5.3492
7.1893
8.8235
5.6970
2.5136
6.8506
3.2634
5.3663
9.0789
sample =
6
5
7
9
6
3
7
3
5
9
generate random integers from rectangular discrete distribution
ranging from 1 to iMax
iMax=10; nSamples=5;
sample = randi(iMax, nSamples, 1)
sample =
7
7
8
2
10
generate random numbers drawn from the standard normal distribution
nSamples = 5; sample = randn(nSamples,1)
mu=0; sigma=1; nSamples=5;
sample = mu + sigma .* randn(nSamples,1)
sample =
1.3959
0.9430
-0.5264
2.2004
1.1068
sample =
-0.3275
-0.3259
-0.1168
-0.5526
-0.2399
draw a sample from a normal distribution of specified mean; std dev
mu=100; sigma=15; nSamples=15;
sample = normrnd(mu, sigma, nSamples, 1)
sample =
73.4265
89.0217
103.9900
99.8874
73.9950
107.5702
92.7374
107.9225
69.6347
120.0430
90.5218
128.2619
96.3719
93.4447
100.7020
draw a random sample from a finite, user-defined population
(with or without replacement)
population = [0 0 0 0 0 0 0 0 0 1 1]; nSamples=10;
bReplacement = true;
sample = randsample(population, nSamples, bReplacement)
mySequence = randsample('ACGT', 24, true, [0.15 0.35 0.35 0.15])
sample =
1 0 0 0 0 0 0 0 0 1
mySequence =
GCGTGCAGGCAGGCGCCGTGCGGT
generate a random permutation for the numbers 1 through N
N=10;
sample = randperm(N)
sample =
6 9 10 4 2 3 7 8 1 5
shuffle the order of the elements in a row vector
data = [10 20 30 40 50 60 70 80 90 100]
order = randperm( length(data) )
shuffled_data = data(order)
data =
10 20 30 40 50 60 70 80 90 100
order =
8 5 1 3 7 10 6 2 9 4
shuffled_data =
80 50 10 30 70 100 60 20 90 40
Roll a die
outcome = randi([1 6],1)
outcome =
2
Flip a coin
outcome = rand < 0.5
outcome = randi([0 1],1)
N=10;
outcome = rand(N,1) < 0.5
outcome = randi([0 1],N,1)
outcome =
1
outcome =
1
outcome =
0
0
1
0
1
1
1
0
0
0
outcome =
0
0
0
1
1
1
0
0
0
1