% Simulation of digital communication system with discrete-amplitude noise:
% Sample code to get you started, including repeated transmission of bit.
% 
% Rich Kozick, Spring 2001

R = 3;        % Number of times to transmit each bit

% Generate signal

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

for r=1:R

% Generate noise

  z = unifrnd(0, 1);
  if (z < 0.1)
    n = -2;
  elseif (z < 0.3)
    n = -1;
  elseif (z < 0.7)
    n = 0;
  elseif (z < 0.9)
    n = +1;
  else
    n = +2;
  end

% Generate observations

  x = s + n;

% Decision algorithm for each bit:
% based on choosing +1 when x = 0.

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

end  % Loop for R repetitions of bit

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

shat_all = median(shat);
if (shat_all ~= s)
  fprintf('Error\n')
else
  fprintf('Correct\n');
end

s
shat

