Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.16 KB | None | 0 0
  1. function x = generate_nums_ber(n, p ,m)
  2. % GENERATE_NUM_BER - generate m outcomes using n bernulli trials
  3.  
  4. %Create vector of size m, go through loop m times
  5. x=zeros(1,m); % 1 x m vector of zeros for storing outcomes
  6. for j=1:m    
  7.   successful_trials = 0;
  8.   for i = 1:n
  9.       u = rand; %between [0,1)
  10.       if(u <= p)
  11.           successful_trials= successful_trials+1;
  12.       end
  13.   end
  14.   x(j)= successful_trials;
  15. end
  16.  
  17. % alternative to loop above: x=(rand(1,m)>=1-p);
  18.  
  19. % plot normalised histogram of outcomes versus theoretical pmf
  20.  
  21. close all;  % close all previous plots
  22.  
  23. alphabet_x=zeros(1,n);        % 1 x n vector with alphabet of r.v.
  24. for i = 1:n+1
  25.     alphabet_x(i) = i-1;
  26. end
  27.    
  28. hx=histc(x,alphabet_x);  % compute histogram of outcomes x on alphabet
  29. stem(alphabet_x,hx/m);   % plot normalised histogram on alphabet
  30. hold on;                 % keep this figure when plotting next
  31. px=zeros(1, n+1);              % theoretical pmf of Ber(p)
  32. for i = 0:n
  33.     px(i+1) = binopdf(i, n, p);
  34. end
  35. stem(alphabet_x,px,'rs'); % plot pmf
  36.  
  37. axis([-1 n+1 0 1]);                  % widen axis of figure
  38. legend('empirical','theoretical'); % add legend to figure
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement