You are on page 1of 3

Lab 3

Simulating Discrete Random Variable


Object:
Compute cdf.
Code:
function f = compute_cdf(px)
n= length(px);
f = zeros(n,1);
f(1) = px(1);
for i= 2:n
f(i) = f(i-1)+ px(i);
end
>> px=[0.1;0.2;0.1;0.2;0.2;0.1];
>> F=compute_cdf(px)
Output:
n =6
F =0.1000
0.3000
0.4000
0.6000
0.8000
0.9000
Object:
Plot F using stairs.
Code: 1
px=[0.1;0.2;0.1;0.2;0.2;0.1];
x=[1;3;4;7;8;9]; 0.9

f=cumsum(px); 0.8

figure(1); 0.7

clf; 0.6

hold on; 0.5


grid; 0.4
f1=[0;f;1];
0.3
x1=[min(x)-1;x;max(x)+1];
0.2
stairs(x1,f1);
plot(x,f,'0'); 0.1

Output: 
0
0 1 2 3 4 5 6 7 8 9 10

Object:
Simulate dice throw.
Code:
num_experiments=1000
count=zeros(1,6)
outcomes=[1,2,3,4,5,6]
for i=1:num_experiments
dice_throw=ceil(6*rand(1))
for j=1:6
if(dice_throw==outcomes(j))
count(j)=count(j)+1
end
end
end
Object: 0.25
Discrete pdf

Plotting discrete pdf.


Code: 0.2
X = [1 2 3 4 5 6];
pdf =[0.2 0.14 0.22 0.16 0.17 0.11];

This is probability of X
stem(X,pdf); 0.15

xlabel('This is the Random Variable


X','FontSize',14);
0.1
ylabel('This is probability of
X','FontName','Times');
title('Discrete 0.05
pdf','FontWeight','b');
Output:  0
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6
This is the Random Variable X

Object:
Plotting cdf.
Code: 1

X = [1 2 3 4 5 6]; 0.9

pdf =[0.2 0.14 0.22 0.16 0.17 0.11]; 0.8

cdf=cumsum(pdf); 0.7

stairs(X(1:1:6),cdf); 0.6

axis([1 6 0 1]); 0.5

Output: 0.4

0.3

0.2

0.1

0
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

Object:
Plotting histogram.
Code:
X = [1 2 3 4 5 6];
pdf =[0.2 0.14 0.22 0.16 0.17 0.11];
for i = 1:100
die_throw=rand(1)
X(1,i) =min(find(die_throw<cdf))
end
hist(X);
Output:
25

20

15

10

0
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

You might also like