% Bilevel signal (NRZ signal)
clear;
R=rand(1,10);
NRZ=2*round(R)-1;
tn=[0:99];
for n=1:100;
    i=fix((n-1)/10)+1;
    s(n)=NRZ(i)+0.1*randn;
end;
figure(1)
subplot(2,1,1)
plot(tn,s);grid on
axis([0 100 -1.1 1.1]);
xlabel('Time t');
ylabel('Received signal s(t)');

% Threshold processing
s_th=0;
for i=1:10;
    s_int=0;
    for j=1:10;
        s_int=s_int+s((i-1)*10+j);
    end;
    if s_int/10 > s_th
        r(i)=1;
    else
        r(i)=-1;
    end;
end;
for n=1:100;
    i=fix((n-1)/10)+1;
    d(n)=r(i);
end;
subplot(2,1,2)
plot(tn,d);grid on
axis([0 100 -1.1 1.1]);
xlabel('Time t');
ylabel('Decoded signal d(t)');

% Multilevel signal 
clear;
k=[1:20];
MLS=round(4*sin(4*pi*(k-1)/20));
tn=[0:99];
for n=1:100;
    i=fix((n-1)/5)+1;
    s(n)=MLS(i)+0.4*randn;
end;
figure(2)
subplot(2,1,1)
plot(tn,s);grid on
axis([0 100 -4.1 4.1]);
xlabel('Time t');
ylabel('Received signal s(t)');

% Threshold processing

for i=1:20;
    s_int=0;
    for j=1:5;
        s_int=s_int+s((i-1)*5+j);
    end;
    r(i)=round(s_int/5);
end;
for n=1:100;
    i=fix((n-1)/5)+1;
    d(n)=r(i);
end;
subplot(2,1,2)
plot(tn,d);grid on
axis([0 100 -4.1 4.1]);
xlabel('Time t');
ylabel('Decoded signal d(t)');

