% MATLAB script for ECS 452 by Asst. Prof. Dr. Prapun Suksompong.

close all; clear all;
tic

%% Simulation parameters
% The number of symbols to be transmitted
n = 1e4; 
% General DMC
% Ex. 3.16 in lecture note
% Channel Input 
S_X = [0 1]; S_Y = [1 2 3];
p_X = [0.2 0.8];
% Channel Characteristics
Q = [0.5 0.2 0.3; 0.3 0.4 0.3];

%% Generating the channel input x
x = randsrc(1,n,[S_X;p_X]); % channel input

%% Applying the effect of the channel to create the channel output y
y = zeros(size(x)); % preallocation
for k = 1:length(x)
    % Look at the channel input one by one. Choose the corresponding row
    % from the Q matrix to generate the channel output.
    y(k) = randsrc(1,1,[S_Y;Q(find(S_X == x(k)),:)]);
end

%% DIY Decoder
Decoder_Table = [0 1 0]; % The decoded values corresponding to the received Y

x_hat = y; % preallocation
for k = 1:length(S_Y)
    I = (y==S_Y(k));
    x_hat(I) = Decoder_Table(k);
end

% When the number of symbols are not too large, show the input string and
% output string on the command window
if n < 200
    num2str(x)
    num2str(y)
    num2str(x_hat)
end

PE_sim = 1-sum(x==x_hat)/n % Error probability from the simulation

% Calculation of the theoretical error probability
PC = 0;
for k = 1:length(S_X)
    I = (Decoder_Table == S_X(k));
    q = Q(k,:); 
    PC = PC+ p_X(k)*sum(q(I));
end
PE_theretical = 1-PC

toc

