%% LTE Symbol Modulation of Data Bits
% This example shows how to use the LTE Symbol Modulator block to modulate 
% data bits to complex data symbols. You can generate HDL code from this 
% block.

% Copyright 2018 The MathWorks, Inc.
%%
% Set up input data parameters. Choose a data length for each modulation 
% type. The data length must be an integer multiple of number of bits per
% symbol.
rng(0);
framesize = 240;

% Map modulation names to values
% 0 - BPSK
% 1 - QPSK
% 2 - 16-QAM
% 3 - 64-QAM
% 4 - 256-QAM
% others - QPSK

% For LTE Symbol Modulator Simulink block
modSelVal = [0;1;2;3;4];

% For |lteSymbolModulate| function
modSelStr = {'BPSK','QPSK','16QAM','64QAM','256QAM'};

outWordLength = 16;
numframes = length(modSelVal);
dataBits  = cell(1,numframes);
modSelTmp = cell(1,numframes);
lteFcnOutput = cell(1,numframes);
%%
% Generate frames of random input samples.

for ii = 1:numframes
    dataBits{ii} = logical(randi([0 1],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 Modulator Simulink block.

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

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

%%
% Run the Simulink model.
modelname = 'ltehdlSymbolModulatorModel';
open_system(modelname);
sim(modelname);

%%
% Export the stream of modulated samples from Simulink to the MATLAB 
% workspace.
sampleOut = squeeze(sampleOut).';
lteHDLOutput = sampleOut(squeeze(validOut));
%%
% Modulate data bits with |lteSymbolModulate| function and use its output as 
% a reference data.
    
for ii = 1:numframes     
    lteFcnOutput{ii} = lteSymbolModulate(dataBits{ii},modSelStr{ii}).';
end  

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

fprintf('\nLTE Symbol Modulator\n');
lteFcnOutput = fi(cell2mat(lteFcnOutput),1,outWordLength,outWordLength-2);
difference = sum(abs(lteHDLOutput-lteFcnOutput(1:length(lteHDLOutput))));
fprintf('\nTotal number of samples differed between Simulink block output and Reference data output: %d \n',difference);
