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

close all; clear all;
tic

%% Simulation parameters
% General DMC
% Ex. 3.16 in lecture note
% Channel Input
S_X = [0 1]; S_Y = [1 2 3];
%p_X = [0.6 0.4];
p_X = [0.2 0.8];
% Channel Characteristics
Q = [0.5 0.2 0.3; 0.3 0.4 0.3];

%% Construct all possible "reasonable" decoders
Decoder_Table_ALL = S_X';
for k = 2:length(S_Y);
    l = size(Decoder_Table_ALL,1);
    t = [];
    for i = 1:length(S_X)
        t = [t; [S_X(i)*ones(l,1) Decoder_Table_ALL]];
    end
    Decoder_Table_ALL = t;
end

%% Calculate the error probability for each of the decoder 
PE_ALL = [];
for k = 1:size(Decoder_Table_ALL,1)
    Decoder_Table = Decoder_Table_ALL(k,:);
    PC = 0;
    for k = 1:length(S_X)
        I = (Decoder_Table == S_X(k));
        Q_row = Q(k,:);
        PC = PC + p_X(k)*sum(Q_row(I));
    end
    PE_theretical = 1-PC;
    PE_ALL = [PE_ALL; PE_theretical];
end

%% Display the results
[Decoder_Table_ALL PE_ALL]

%% Find the optimal detectors
Min_PE = min(PE_ALL)
I = [abs(PE_ALL-Min_PE)<1e-10];
Optimal_Detector = Decoder_Table_ALL(I,:)

toc

