Search code examples
matlabprobability-theory

Is there a faster way to calculate the expected value?


So for my probability class, my professor asked the following question on a homework problem:

A fair coin is flipped 10,000 times. Let X correspond to the difference between the number of heads and the number of tails. Using MATLAB, compute the expected value of X.

This is what I wrote to answer the question:

N = 10000;
i =0;
r=1/2;
Q=nchoosek(N,(X+N)/2);
X=(1,N);

for i=-N:N
    P=Q*r.^(X+N)/2*(1-r)^(N-(X+N)/2) % probability_mass_function
    E=sum(abs(X).*P); % expected value

end

However, is there faster and quicker way to compute this expected value? Any help would be greatly appreciated. Thanks


Solution

  • You can put all tests results in single matrix in one line and then calculate X per test, then average over X:

    clear
    
    TAIL=0; HEAD=1; 
    
    NumTests=121;
    
    NumRollsPerTest=10*1000;
    
    AllTestsRolls= rand(NumTests,NumRollsPerTest)>0.5 ; %head when rand>0.5
    
    XperTest=sum(AllTestsRolls==HEAD,2)-sum(AllTestsRolls==TAIL,2);%every row is test so calc per test
    
    ExpectedX=sum(XperTest)/length(XperTest)