How to use hold on command to put curves generated by two seperate algorithms on same figure?

3 views (last 30 days)
Both of these algorithms are mentioned below!!!
%% Testing
%
% This script
% 1. generates testing data for each SNR point;
% 2. calculates the symbol error rate (SER) based on deep learning (DL),
% least square (LS) and minimum mean square error (MMSE).
%% Clear workspace
clear variables;
close all;
%% Load common parameters and the trained NN
load('SimParametersPilot64.mat');
load('TrainedNetPilot64.mat');
%% Other simulation parameters
NumPilot = length(FixedPilot);
PilotSpacing = NumSC/NumPilot;
NumOFDMsym = NumPilotSym+NumDataSym;
NumClass = length(Label);
NumPath = length(h);
% Load pre-calculated channel autocorrelation matrix for MMSE estimation
% This autocorrelation matrix is calculated in advance using the 3GPP
% channel model, which can be replaced accordingly.
load('RHH.mat');
%% SNR range
Es_N0_dB = 0:2:20; % Es/N0 in dB
Es_N0 = 10.^(Es_N0_dB./10); % linear Es/N0
N0 = 1./Es_N0;
NoiseVar = N0./2;
%% Testing data size
NumPacket = 10000; % Number of packets simulated per iteration
%% Simulation
% Same pilot sequences used in training and testing stages
FixedPilotAll = repmat(FixedPilot,1,1,NumPacket);
% Number of Monte-Carlo iterations
NumIter = 1;
% Initialize error rate vectors
SER_DL = zeros(length(NoiseVar),NumIter);
SER_LS = zeros(length(NoiseVar),NumIter);
SER_MMSE = zeros(length(NoiseVar),NumIter);
for i = 1:NumIter
for snr = 1:length(NoiseVar)
%% 1. Testing data generation
noiseVar = NoiseVar(snr);
% OFDM pilot symbol (can be interleaved with random data symbols)
PilotSym = 1/sqrt(2)*complex(sign(rand(NumPilotSym,NumSC,NumPacket)-0.5),sign(rand(NumPilotSym,NumSC,NumPacket)-0.5));
PilotSym(1:PilotSpacing:end) = FixedPilotAll;
% OFDM data symbol
DataSym = 1/sqrt(2)*complex(sign(rand(NumDataSym,NumSC,NumPacket)-0.5),sign(rand(NumDataSym,NumSC,NumPacket)-0.5));
% Transmitted OFDM frame
TransmittedPacket = [PilotSym;DataSym];
% Received OFDM frame
ReceivedPacket = genTransmissionReceptionOFDM(TransmittedPacket,LengthCP,h,noiseVar);
% Collect the data labels for the selected subcarrier
DataLabel = zeros(size(DataSym(:,idxSC,:)));
for c = 1:NumClass
DataLabel(logical(DataSym(:,idxSC,:) == 1/sqrt(2)*Mod_Constellation(c))) = Label(c);
end
DataLabel = squeeze(DataLabel);
% Testing data collection
XTest = cell(NumPacket,1);
YTest = zeros(NumPacket,1);
for c = 1:NumClass
[feature,label,idx] = getFeatureAndLabel(real(ReceivedPacket),imag(ReceivedPacket),DataLabel,Label(c));
featureVec = mat2cell(feature,size(feature,1),ones(1,size(feature,2)));
XTest(idx) = featureVec;
YTest(idx) = label;
end
YTest = categorical(YTest);
%% 2. DL detection
YPred = classify(Net,XTest,'MiniBatchSize',MiniBatchSize);
SER_DL(snr,i) = 1-sum(YPred == YTest)/NumPacket;
%% 3. LS & MMSE detection
% Channel estimation
wrapper = @(x,y) performChanEstimation(x,y,RHH,noiseVar,NumPilot,NumSC,NumPath,idxSC);
ReceivedPilot = mat2cell(ReceivedPacket(1,:,:),1,NumSC,ones(1,NumPacket));
PilotSeq = mat2cell(FixedPilotAll,1,NumPilot,ones(1,NumPacket));
[EstChanLS,EstChanMMSE] = cellfun(wrapper,ReceivedPilot,PilotSeq,'UniformOutput',false);
EstChanLS = cell2mat(squeeze(EstChanLS));
EstChanMMSE = cell2mat(squeeze(EstChanMMSE));
% Symbol detection
SER_LS(snr,i) = getSymbolDetection(ReceivedPacket(2,idxSC,:),EstChanLS,Mod_Constellation,Label,DataLabel);
SER_MMSE(snr,i) = getSymbolDetection(ReceivedPacket(2,idxSC,:),EstChanMMSE,Mod_Constellation,Label,DataLabel);
end
end
SER_DL = mean(SER_DL,2).';
SER_LS = mean(SER_LS,2).';
SER_MMSE = mean(SER_MMSE,2).';
figure();
semilogy(Es_N0_dB,SER_DL,'r-o','LineWidth',2,'MarkerSize',10);hold on;
semilogy(Es_N0_dB,SER_LS,'b-o','LineWidth',2,'MarkerSize',10);hold on;
semilogy(Es_N0_dB,SER_MMSE,'k-o','LineWidth',2,'MarkerSize',10);hold off;
legend('Deep learning (DL)','Least square (LS)','Minimum mean square error (MMSE)');
xlabel('SNR');
ylabel('Bit error rate (BER)');
%%
function [EstChanLS,EstChanMMSE] = performChanEstimation(ReceivedData,PilotSeq,RHH,NoiseVar,NumPilot,NumSC,NumPath,idxSC)
% This function is to perform LS and MMSE channel estimations using pilot
% symbols, second-order statistics of the channel and noise variance [1].
% [1] O. Edfors, M. Sandell, J. -. van de Beek, S. K. Wilson and
% P. Ola Borjesson, "OFDM channel estimation by singular value
% decomposition," VTC, Atlanta, GA, USA, 1996, pp. 923-927 vol.2.
PilotSpacing = NumSC/NumPilot;
%%%%%%%%%%%%%%% LS estimation with interpolation %%%%%%%%%%%%%%%%%%%%%%%%%
H_LS = ReceivedData(1:PilotSpacing:NumSC)./PilotSeq;
H_LS_interp = interp1(1:PilotSpacing:NumSC,H_LS,1:NumSC,'linear','extrap');
H_LS_interp = H_LS_interp.';
%%%%%%%%%%%%%%%% MMSE estimation based on LS %%%%%%%%%%%%%%%%
[U,D,V] = svd(RHH);
d = diag(D);
InvertValue = zeros(NumSC,1);
if NumPilot >= NumPath
InvertValue(1:NumPilot) = d(1:NumPilot)./(d(1:NumPilot)+NoiseVar);
else
InvertValue(1:NumPath) = d(1:NumPath)./(d(1:NumPath)+NoiseVar);
end
H_MMSE = U*diag(InvertValue)*V'*H_LS_interp;
%%%%%%%%%%%%%%% Channel coefficient on the selected subcarrier %%%%%%%%%%%
EstChanLS = H_LS_interp(idxSC);
EstChanMMSE = H_MMSE(idxSC);
end
%%
function SER = getSymbolDetection(ReceivedData,EstChan,Mod_Constellation,Label,DataLabel)
% This function is to calculate the symbol error rate from the equalized
% symbols based on hard desicion.
EstSym = squeeze(ReceivedData)./EstChan;
% Hard decision
DecSym = sign(real(EstSym))+1j*sign(imag(EstSym));
DecLabel = zeros(size(DecSym));
for c = 1:length(Mod_Constellation)
DecLabel(logical(DecSym == Mod_Constellation(c))) = Label(c);
end
SER = 1-sum(DecLabel == DataLabel)/length(EstSym);
end
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
%% Step 1: Configurations
clc;
%clear all;
close all;
save_tx_data = 1;
if save_tx_data
mkdir('mat');
end
% 1.1 OFDM parameters
N = 64; % FFT size, Number of total subcarriers
Ncp = 16; % Length of Cyclic prefix
Ts = 1e-7; % Sampling period of channel
Fd = 0; % Max Doppler frequency shift
Np = 8; % No of pilot symbols
Ng = 4; % No of side guard subcarriers
Ndc = 2; % No of DC guard subcarriers
Ndata = N - Np - 2.*Ng - Ndc; % No of Data subcarriers per symbol
Frame_size = 8; % OFDM symbols per frame
Nframes = 2000; % Size of tested OFDM frames: set as 10^4 for smooth curve
M_set = [2, 4, 8, 16]; % Modulation orders
SNRs = -10:1:29; % Test SNR points
% 1.2 Vehicles for results
berofdm_all = zeros(5,length(SNRs));
berofdm_all(1,:) = SNRs;
serofdm_all = zeros(5,length(SNRs));
serofdm_all(1,:) = SNRs;
% 1.3 Calculate pilot locations
DC_sc = [N/2, N/2+1];
Effec_sc = [Ng+1:N-Ng];
Effec_sc = setdiff(Effec_sc, DC_sc);
% Pilot_sc = [5,12,19,26,34,41,48,55];
pilot_loc = [1:ceil(length(Effec_sc)/Np):length(Effec_sc)];
Pilot_sc = Effec_sc(pilot_loc);
guard_sc = [1:Ng,N-Ng+1:N];
Np = length(pilot_loc); % Recalculate Number of pilot
pilot_sc_frame = [];
guard_sc_frame = [];
DC_sc_frame = [];
for i_sym = 0:Frame_size-1
pilot_sc_sym = Effec_sc(sort(mod((pilot_loc + i_sym*3)-1,length(Effec_sc))+1)); % scattered
% pilot_sc_sym = Pilot_sc; % comb pilot
pilot_sc_frame = [pilot_sc_frame, pilot_sc_sym+i_sym*N];
guard_sc_frame = [guard_sc_frame, guard_sc+i_sym*N];
DC_sc_frame = [DC_sc_frame, DC_sc+i_sym*N];
end
data_sc_frame = setdiff([1:Frame_size*N],guard_sc_frame);
data_sc_frame = setdiff(data_sc_frame, pilot_sc_frame);
data_sc_frame = setdiff(data_sc_frame, DC_sc_frame);
%% Step 2: Test Loops
mod_names = {'BPSK','QPSK','8QAM','16QAM'};
channel = 'AWGN';
mat_name = sprintf('BER_OFDM_%s_Gray.mat',channel);
csv_name = sprintf('BER_OFDM_%s_Gray.csv',channel);
snr = SNRs;
% EsNo= EbNo + 10*log10((N-2.*Np)/N)+ 10*log10(N/(N+Ncp)); % symbol to noise ratio
% snr= EsNo - 10*log10(N/(N+Ncp));
for m_ary = 1:4
M = M_set(m_ary); % No of symbols for PSK modulation
const = qammod([0:M-1],M,'gray'); % Get constellation
berofdm = zeros(1,length(snr));
serofdm = zeros(1,length(snr));
for i = 1:length(snr)
% Step 2.1 Transmitter
% 2.1.1 Random bits generation
D = round((M-1)*rand(Ndata*Frame_size,Nframes));
D_test = reshape(D, Ndata, Frame_size*Nframes);
D_gray = D_test; % gray2bin(D_test,'qam',M);
txbits = de2bi(D_gray(:)); % transmitted bits
% 2.1.2 Modulation
if M == 8
Dmod = qammod(D,M,'gray');
else
Dmod = qammod(D,M,'gray');
end
% 2.1.3 Framing
Data = zeros(N*Frame_size,Nframes); % Guard sc Insertion
Data(data_sc_frame,:) = Dmod; % Data sc Insertion
txamp = max(abs(Dmod(:)));
pilot_signal = txamp.*sqrt(1/2).*(1+1i); % Norm pilot power to peak constellation power
Data(pilot_sc_frame,:)= pilot_signal; % Pilot sc Insertion
Data = reshape(Data, N, Frame_size*Nframes);
% 2.1.4 To Time-domain OFDM symbol
IFFT_Data = (N/sqrt(N-2*Np))*ifft(Data,N);
TxCy = [IFFT_Data((N-Ncp+1):N,:); IFFT_Data]; % Add Cyclic prefix
[r, c] = size(TxCy);
Tx_Data = TxCy;
% 2.1.5 Clip PAPR to 8 (9dB)
Tx_Amp = abs(Tx_Data);
Tx_Power = Tx_Amp.^2;
Power_PAPR8 = 8.*mean(Tx_Power,1);
Clip_loc = Tx_Power > Power_PAPR8;
Clip_Data = Tx_Data./Tx_Amp;
Clip_Data = sqrt(Power_PAPR8).*Clip_Data;
Tx_Data(Clip_loc) = Clip_Data(Clip_loc);
% Step 2.2 Wireless Channel
Tx_Pow_Freq = mean2(abs(Tx_Data).^2);
Tx_Data = reshape(Tx_Data, r*Frame_size,[]);
totalFrames = c/Frame_size;
% 2.2.2 Add AWGN noise
y = awgn(Tx_Data,snr(i),'measured');
y = reshape(y,r,[]);
% Step 2.3: OFDM Receiver
% 2.3.1 Remove cyclic prefix
Rx = y(Ncp+1:r,:);
% 2.3.2 Transform to Frequency-Domain
Rx_Freq = (sqrt(N-2*Np)/N)*fft(Rx,N,1);
% 2.3.3 Reshape to Frame size
FFT_Data = reshape(Rx_Freq,N*Frame_size,[]);
% 2.3.4 Extract Data Cells
FFT_Data = reshape(FFT_Data(data_sc_frame,:), [], Nframes*Frame_size);
% 2.3.5 Demodulation
if m_ary==3
Rx_Data = qamdemod(FFT_Data,M,'gray');
else
Rx_Data = qamdemod(FFT_Data,M,'gray');
end
Rx_gray = Rx_Data; % gray2bin(Rx_Data,'qam',M);
rxbits = de2bi(Rx_gray(:));
% Step 2.4 Collect BER and SER
[bitErrors,ber] = biterr(txbits,rxbits);
[symErrors,ser] = symerr(Rx_Data(:),D(:));
serofdm(i) = ser;
berofdm(i) = ber;
% Export data for Test in python
if save_tx_data
filename = sprintf('./mat/ofdm_awgn_%s_%ddB.mat',mod_names{m_ary},snr(i));
save(filename,'y','txbits','rxbits');
end
end
berofdm_all(m_ary+1,:) = berofdm;
serofdm_all(m_ary+1,:) = serofdm;
end
%% Step 3: Result Presentation: Plot BER
save(mat_name, 'berofdm_all','serofdm_all');
csvwrite(csv_name, berofdm_all);
figure;
semilogy(SNRs,berofdm_all(2:5,:),'--x','LineWidth',2);
grid on;
title('OFDM BER vs SNR in AWGN channel');
xlabel('SNR (dB)');
ylabel('BER');
legend(mod_names);

Answers (0)

Categories

Find more on Propagation and Channel Models in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!