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

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

% Generate transmitted signal

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

for t=1:T

% Generate channel 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 at receiver

  x = s + n;

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

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

end  % Loop for T repetitions of bit

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

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

s
shat

