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

close all; clear all;
tic

%% Simulation parameters
% Channel Input 
S_X = [0 1]; S_Y = [0 1];
p0 = 0.8; p1 = 1-p0; p_X = [p0 p1];
% Channel Characteristics
p = 0.1; Q = [1-p p; p 1-p];

%% All possible "reasonable" decoders
% X_hat = Y; X_hat = 1-Y; X_hat = 1; X_hat = 0
Decoder_Table_ALL = [0 1; 1 0; 1 1; 0 0] 

%% 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
[V I] = min(PE_ALL);
Optimal_Detector = Decoder_Table_ALL(I,:)
Min_PE = V

toc

