% binomial.m % This MATLAB code simulates a binomial distribution % You are prompted to supply % the number of tosses to make, the number of % simulations to run, and the probability of a head. % % The output will be vector: x contains the number of % heads on each toss. A histogram for x is plotted % along with the mean and standard deviation for both % the vector x and the theoretical mean and variance for % the binomial. !c: n=input('how many tosses to make: ') p=input('probability of a head: ') m=input('how many simulations to run: ') kj=0; kheads=0; ktails=0; for j=1:m for i=1:n a=rand(1,1); if a <= p kheads=kheads+1; else ktails=ktails+1; end; end; x(j)=kheads; kheads=0; end; xbar=mean(x); stan=std(x); disp('mean and standard deviation are') xbar,stan,pause a=n*p; b=sqrt(a*(1-p)); disp('np and sqrt(np(1-p)) are') a,b,pause hist(x) title('histogram for m tosses'),pause