Random Numbers
·
Pseudo-random numbers can be generated in
MATLAB using the following built-in functions:
1. random – generates most any type of random numbers
2. rand – generates uniform random numbers ranging from 0 to 1
3. randn – generated Gaussian random numbers with mean zero and standard
deviation 1
·
Use the help command to learn about these
functions and try them out
·
Learn about the “hist” function for
plotting a histogram from a set of data.
A histogram is a plot showing how many numbers fall within specific
ranges.
·
Generate a “bell” curve using the
following commands
x=randn(1,1000);
hist(x,20)
xlabel('value')
ylabel('number of occurances')
·
Let’s model the throwing of darts for
example. The x,y position of each dart
relative to the center (0,0) is a random variable. We can generate realizations of these random variables as follows
x=randn(1,1000);
y=randn(1,1000);
figure
plot(x,y, 'rx')
xlabel('x')
ylabel('y')
·
Let’s compute the number of darts outside
of a 1 unit radius
% radius of each
“dart”
r=sqrt(x.^2+y.^2);
I=find( r > 1); % find is a powerful command, use help to learn about it
S=sprintf('The number of
darts that were outside a 1 unit radius circle is %d', length(I) );
disp(S)
S=sprintf('The probability
that any given dart is outside a 1 unit radius circle is %.2f', length(I)/length(r)
);
disp(S)
·
What is the probability that after
flipping a coin 3 times and getting 3 heads, the next one is heads? Some may think that the probability of
getting heads on the 4 try is lower, but in fact this is not true. Given the 3 previous flips are “in the
record books” the probability of the next flip is still 50/50. Let’s test this
num_trials = 10000;
heads = rand( 4, num_trials
) > .5;
num_heads_in_4 = sum( heads );
I = find( num_heads_in_4
== 4 );
prob_4_in_4 = length(I)/num_trials;
disp(sprintf('The probability
of getting 4 heads in a row is %.2f', prob_4_in_4) )
num_heads_in_first_3=sum(
heads(1:3,:) );
I = find(num_heads_in_first_3
== 3);
heads_on_4_after_3
= heads( 4, I );
prob_4_after_3 = sum(heads_on_4_after_3)/length(heads_on_4_after_3);
disp(sprintf('The probability
of getting a 4th heads after 3 in a row is %.2f', prob_4_after_3 ) )