%This is a sample code to show how to generate a discrete random variable
%that takes only a finite number of possible values. We then average 10,000
%realizations to produce an estimate of E X.
%The inputs:
% N = the number of random variables I want to average over.
% This will be 10,000.
%The ouput:
% average = The estimate for E X.
%How to call this function: put this script into the folder in which
%Matlab is open. Then type the following into Matlab:
% [average] = RV_Avg(10000);
function [average] = RV_Avg(N)
%I am storing the data. The command zeros([a,b]), creates an array (or
% matrix) of all zeros that is of size a X b. I am making a single column
%vector to hold the data.
data = zeros([N,1]);
%These are the values for the random variable.
a = [-1 5 10 100];
%These are the associated probabilities
p = [1/5 1/7 1/2 11/70];
%The main FOR LOOP. It runs from 1 through N, generating a single
%random variable each step.
for j = 1:N
%generate a uniform(0,1) random variable
u = rand;
%sum will be used to determine when I have added enough
sum = 0;
if p(1) > u
data(j) = a(1);
elseif p(1) + p(2) > u
data(j) = a(2);
elseif p(1) + p(2) + p(3) > u
data(j) = a(3);
else
data(j) = a(4);
end
end
average = 0;
for ell = 1:N
average = average + data(ell);
end
average = (1/N)*average;
end