% Simulation of digital communication system with Gaussian noise
% and transmission of each bit R times (odd R).
% 
% Rich Kozick,

clear
RUNs = 1e4;   % Total number of trials to perform
R = 3;        % Number of times to transmit each bit

error_count = 0;

SNRdB = 5;
Nvar = 10.^(-SNRdB/10);
Nstd = sqrt(Nvar);

for k=1:RUNs

% Generate signal

  z = unifrnd(0, 1);
  if (z < 0.5)
    s = -1;
  else
    s = +1;
  end

for r=1:R

% Generate noise

n = normrnd(0, Nstd);   % Gaussian (normal) noise

% Generate observations

  x = s + n;

% Decision algorithm for each bit

if (x <= 0)
    shat(r) = -1;
  else
    shat(r) = +1;
  end

end

% Take majority of the R bit decisions as the overall decision

shat_all = median(shat);
if (shat_all ~= s)
  error_count = error_count + 1;
end

end

fprintf('Repeat %d times: %d errors in %d runs ==> probability of error = %f\n', R, error_count, RUNs, error_count/RUNs);
fprintf('Analytical P[error] = %f\n', normcdf(-1, 0, Nstd))
