%% LTE Symbol Demodulation of Complex Data Symbols
% This example shows how to use the LTE Symbol Demodulator block to demodulate complex LTE data symbols to data bits or LLR values. 
% The workflow follows these steps:
%
% # Set up input data parameters.
% # Generate frames of random input samples.
% # Convert framed input data to a stream of samples and import the stream into Simulink(R).
% # Run the Simulink(R) model, which contains the LTE Symbol Demodulator block.
% # Export the stream of demodulated samples from Simulink to the MATLAB(R) workspace.
% # Demodulate data symbols with |lteSymbolDemodulate| function to use its output as a reference data.
% # Compare Simulink block output data with the reference MATLAB function output.

% Copyright 2019 The MathWorks, Inc.

%% 
% Set up input data parameters.
%
% Map modulation names to values. The numerical values are used to set up 
% the LTE Symbol Demodulator block. The strings are used to configure the
% |lteSymbolDemodulator| function.

rng(0);
framesize = 10;

% 0 - BPSK
% 1 - QPSK
% 2 - 16-QAM
% 3 - 64-QAM
% 4 - 256-QAM
% others - QPSK
modSelVal = [0;1;2;3;4];
modSelStr = {'BPSK','QPSK','16QAM','64QAM','256QAM'};

decType = 'Soft';

numframes = length(modSelVal);
dataSymbols  = cell(1,numframes);
modSelTmp = cell(1,numframes);
lteFcnOutput = cell(1,numframes);

%% 
% Generate frames of random input samples.

for ii = 1:numframes
    dataSymbols{ii} = complex(randn(framesize,1),randn(framesize,1));
    modSelTmp{ii} = fi(modSelVal(ii)*ones(framesize,1),0,3,0);
end

%%
% Convert the framed input data to a stream of samples and input the
% stream to the LTE Symbol Demodulator Simulink block.

idlecyclesbetweensamples = 0;
idlecyclesbetweenframes  = 0;
[sampleIn, ctrl] = whdlFramesToSamples(dataSymbols,idlecyclesbetweensamples,...
    idlecyclesbetweenframes);
[modSel, ~] = whdlFramesToSamples(modSelTmp,idlecyclesbetweensamples,...
    idlecyclesbetweenframes);
validIn = logical(ctrl(:,3)');

sampletime = 1;
samplesizeIn = 1;
simTime = size(ctrl,1)*8;

%%
% Run the Simulink model.

modelname = 'ltehdlSymbolDemodulatorModel';
open_system(modelname);
set_param([modelname '/Demod/LTE Symbol Demodulator'],'DecisionType',decType)
sim(modelname);

%%
% Export the stream of demodulated samples from Simulink to the MATLAB 
% workspace.

lteHDLOutput = sampleOut(validOut).';

%%
% Demodulate data symbols with |lteSymbolDemodulate| function and use its 
% output as a reference data.

for ii = 1:numframes     
 lteFcnOutput{ii} = lteSymbolDemodulate(dataSymbols{ii},modSelStr{ii},decType).';
end 

%%
% Compare the output of the Simulink model against the output of 
% |lteSymbolDemodulate| function.

lteFcnOutput = double(cell2mat(lteFcnOutput));

figure(1)
stem(lteHDLOutput,'b')
hold on
stem(lteFcnOutput,'--r')
grid on
legend('Reference','Simulink')
xlabel('Sample Index')
ylabel('Magnitude')
title('Comparison of Simulink block and MATLAB function')

