In: Statistics and Probability
A binomial random variable with parameters n and p represents the number of successes in n independent trials. We can obtain a binomial random variable by generating n uniform random numbers 1 2 n U ,U ,...,U and letting X be the number of i U that are less than or equal to p. (a) Write a MATLAB function to implement this algorithm and name the function gsbinrnd. You may use the for loop to generate random numbers. (b) Use the function you have written to generate a set of random variables that are distributed according to the binomial distribution. You may use the following parameters n = 6 and p = 0.5. (c) Plot the histogram for the binomial random variables generated.
a) MATLAB function to generate Binomial rv
Save this in a file called gsbinrnd.m
b) In another file write the following to call the above function to generate some variables
get the following output
c) plot the histogram
output
all code in text format
%% The following code is for the function to be saved in a file named gsbinrnd.m
function X= gsbinrnd(n,p)
%Initialize the value of X
X=0;
%using for loop generate n random numbers
for i = 1:n
%generate uniform random number in (0,1) using rand()
if rand(1,1)<=p
%if the uniform random number is less than p then increment X
X=X+1;
end;
end;
end
%%%Following code is for the main program%%%%%%%
rand('state',0);
%set the values of n and p
n=6;
p=0.5;
%number of random numbers to be generated
r=100;
%initialize Y to hold RVs
Y=[];
%generate r number of Binomial RV
for i=1:r
%call the function gsbinrnd(n,p)
Y=[Y;gsbinrnd(n,p)];
end
fprintf('\nBinomial RV for n=%.0f and p=%.2f are \n\t',n,p);
fprintf('%.0f,',Y);
%plot the histogram
%get the histogram frequencies for each bin
hist(Y,6);
title(sprintf('Distribution of Binomial RV for
n=%.0f,p=%.2f',n,p));
xlabel('Binomial RV');
ylabel('Frequency');