Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(1) Using the Matlab code developed in Software Assignment #1: Convert the code

ID: 3840343 • Letter: #

Question

(1) Using the Matlab code developed in Software Assignment #1:

Convert the code that generates the random number (H,T) with equal probabilities

into a function called myBernolli(p,S) that takes as an input the probability of successp and S is the outcome defined as success (either T or H) and returns the outcome of the trial (either T or H).

Test that your function is actually producing the success outcome with probability p by running the function in a loop of 1000 trials and counting how many times success is produced (it should be close to p*1000).

Write a Matlab function called myBinomial(n,p) that takes as an input the total number of trials n, the probability of success p and the outcome defined as success S and uses myBernolli() to return as an output the number of successes x.

Write a Matlab function called myGeometric() that takes as an input the probability of success p and the outcome defined as success S and uses myBernolli() to return as an output the number of trials till first success x.

Verify that myBinomial() and myGeometric() generates values that follows Binomial and Geometric Distributions by running each of them 5000 times in a loop and plotting a histogram of the random variable x generated from each.

Explanation / Answer

mybernoulli.m

function [outc]=mybernoulli(p,S)
if S=='H'
SN='T';
elseif S=='T'
SN ='H';
end

prob=[p 1-p];
outc=sum(rand >= cumsum([0 , prob]));
if outc ==1
outc=S;
else
outc=SN;
end
end

testbernoulli.m

clc
clear all
suc=0;
fail=0;
p=input('Enter Probability::');
if p>1
fprintf('Invalid Input using Default p=0.5');
p=0.5;
end
S=input('Enter Sucess Output (T :: H)','s');
for i=1:1000
a(i)=mybernoulli(p,S);
if a(i)== S
suc=suc+1;
else
fail=fail+1;
end
end

suc
fail

mybinomial.m

function [nsuc]=mybinomial(p,S,n)
nsuc=0;
for i=1:n
a(i)= mybernoulli(p,S);
if a(i)==S
nsuc=nsuc+1;
end
end
end

mygeometric.m

function [t]=mygeometric(p,S,n)
t=0;
for i=1:n
b(i)=mybernoulli(p,S);
if b(i)== S
t=i;
break;
end
end
end

testgeometric.m

clc
clear all
p=input('Enter Probability::');
if p>1
fprintf('Invalid Input using Default p=0.5');
p=0.5;
end
S=input('Enter Sucess Output (T :: H)','s');
n=input('Total number of trials::');
for i=1:5000
sucb(i)=mybinomial(p,S,n);
sucg(i)=mygeometric(p,S,n);
end
figure(1);
hist(sucb);
figure(2);
hist(sucg);

testbinomial.m

clc
clear all
p=input('Enter Probability::');
if p>1
fprintf('Invalid Input using Default p=0.5');
p=0.5;
end
S=input('Enter Sucess Output (T :: H)','s');
n=input('Total number of trials::');
suc=mybinomial(p,S,n);