function [Pe, SNR] = fading_error_nc(SNR_min,SNR_max,SNR_step,errorCount)
% simulates noncoherent detection for orthogonal signaling over a flat
% Rayleigh fading channel
% The error probability Pe is evaluated using Monte Carlo simulation for
% several SNR values between SNR_min and SNR_max, with stepsize SNR_step;
% SNR is measured in dB.
% For each SNR value, as many transmissions are simulated as needed to
% obtain at least errorCount errors.
blocklength = 1000; % number of simultaneous transmissions
counter = 0; % for matrix indexing
for snr = SNR_min:SNR_step:SNR_max % for evey SNR value
counter = counter + 1;
snrLin = 10^(snr/10); % linear SNR
symbolCount = 0; % number of transmitted symbols
errors = 0; % number of errors so far
while errors < errorCount % check number of errors
symbolCount = symbolCount + blocklength;
% the symbols are the rows of this matrix, each row has exactly one
% "0" and one "1"
sig = randerr(blocklength,2);
% the noise power is normalized to one, hence the signal power is
% equal to 2*snrLin, because we need to average over two time slots
txSig = sqrt(2*snrLin)*sig;
% the channel, normalized to unit power, i.e., no path loss
h = sqrt(1/2)*(randn(blocklength, 2)+ i*randn(blocklength,2));
% complex Gaussian noise, unit variance
w = 1/sqrt(2)*(randn(blocklength, 2) + i*randn(blocklength,2));
% modulate with the channel, add noise
rxSig = h.* txSig + w ;
% square law receiver
rxStat = abs(rxSig).^2;
% the noncoherent detector: check which of the two time slots
% contains more energy
decision = rxStat(:,1) >= rxStat(:,2);
errors = errors + sum(abs(sig(:,1) - decision)); % count errors
end
Pe(counter) = errors / symbolCount; % estimate error probability
SNR(counter) = snr;
end