% Monte Carlo version of matchfilt.m to tabulate results over many runs.
% R. Kozick, ELEC 476, Fall 2001

RUNS = 1e4;	% Number of runs to tabulate

dt = .01;
t=-1:dt:1;
T = length(t);

% Generate pulse shapes

prect = ones(1,T);
ptri(1:(T-1)/2) = t(1:(T-1)/2)+1;
ptri((T-1)/2+1) = 1;
ptri((T+1)/2:T) = 1-t((T+1)/2:T);
ptri = ptri * sqrt(3);   % Scale so rect and tri pulses have same energy

% Change the noise amplitude with wstddev
wstddev = 10;

randn('seed', sum(100*clock));	% Randomize the random number seed
rf1sum = 0;
rf2sum = 0;
mf2sum = 0;
sm1sum = 0;
sm2sum = 0;

for run=1:RUNS

w = wstddev*randn(1,T);  % Gaussian noise

% Add noise to the pulses
pw1 = prect + w;
pw2 = ptri + w;

% Filter the pulses 

rf1 = sum(pw1);
rf2 = sum(pw2);
mf2 = sum(ptri.*pw2);
mT = (T+1)/2;        % Sample at midpoint of pulse
sm1 = pw1(mT);
sm2 = pw2(mT);

if rf1 < 0
  rf1sum = rf1sum + 1;
end
if rf2 < 0
  rf2sum = rf2sum + 1;
end
if mf2 < 0
  mf2sum = mf2sum + 1;
end
if sm1 < 0
  sm1sum = sm1sum + 1;
end
if sm2 < 0
  sm2sum = sm2sum + 1;
end

end	% End of RUNS loop

fprintf('Probability of incorrect decision for each method with %d runs:\n\n', RUNS);
fprintf('\tRect pulse, rect filter:  %f\n', rf1sum/RUNS)
fprintf('\tTri  pulse, rect filter:  %f\n', rf2sum/RUNS)
fprintf('\tTri  pulse, tri  filter:  %f\n', mf2sum/RUNS)
fprintf('\tRect pulse,  mid sample:  %f\n', sm1sum/RUNS)
fprintf('\tTri  pulse,  mid sample:  %f\n', sm2sum/RUNS)
