% EE278B Homework 1 Problem 8

% The following code finds the empirical pdf and cdf for 2
% predetermined number of samples for Homework 1, Problem 8.
% The pdf part is for interest only.

clear all;
clf;

sample_count_array = [ 100 5000 ];

for sample_count_index = 1:2

  number_of_samples = sample_count_array( sample_count_index );

  % Sample a sequence of values of a uniform random variable
  X = rand( 1, number_of_samples );

  % WRITE MATLAB CODE HERE to generate Y (gaussian random
  % variables) from X
  % hint: use the norminv comand
  Y = norminv(X,2,sqrt(4));

  % Find the histogram of samples
  [ histogram bin_centres ] = hist( Y, sqrt( number_of_samples ) );

  % Find the difference of neighboring points in the histogram
  bin_width = bin_centres(2) - bin_centres(1);

  % Convert histogram points to pdf samples, with "integral" = 1
  pdf_samples = histogram/number_of_samples/bin_width;

  % Plot empirical pdf
  subplot( 2, 2, 2*( sample_count_index - 1 ) + 1 );
  plot( bin_centres, pdf_samples );

  % On the same plot
  hold on

  % Plot the true pdf
  plot( bin_centres, normpdf( bin_centres, 2, 2 ), 'r:' );
  title( [ 'Empirical pdf (solid) and true pdf (dotted), ' ...
         num2str( number_of_samples ), ' samples' ] );

  % WRITE MATLAB CODE HERE to find the empirical cdf from the histogram
  % hint: use the sum and cumsum commands
  empirical_cdf = cumsum(pdf_samples)/sum(pdf_samples);

  % On a different plot compare cdfs
  subplot( 2, 2, 2*( sample_count_index - 1 ) + 2 );

  plot( bin_centres, empirical_cdf )
  hold on

  % True cdf
  plot( bin_centres, normcdf( bin_centres, 2, 2 ), 'r:' );

  title( [ 'Empirical cdf (solid) and true cdf (dotted), ' ...
           num2str( number_of_samples ), ' samples' ] );

end

% Produce postscript file for hardcopy
orient landscape
print -depsc2 hw1q8
