%% OFDM Modulation of LTE Resource Grid Samples
% This example shows how to use the LTE OFDM Modulator block to modulate
% LTE resource grid samples to an equivalent time-domain signal output.
% You can generate HDL code from this block.

% Copyright 2018 The MathWorks, Inc.

%%
% Generate the input resource grid using LTE Toolbox(TM). 

enb = lteRMCDL('R.6');
enb.CyclicPrefix='Normal';
enb.TotSubframes = 1;
% --------------------------------------------------------------
%      NDLRB              |   Sampling Rate (MHz)
% --------------------------------------------------------------
%       6                  |   R.4
%       15                 |   R.5
%       25                 |   R.6
%       50                 |   R.7
%       75                 |   R.8
%       100                |   R.9
% --------------------------------------------------------------

[~,LTEGrid,info] = lteRMCDLTool(enb,[1;0;0;1]);
[eNodeBOutput,~] = lteOFDMModulate(enb,LTEGrid);

%%
% Convert the |LTEGrid| sample frames to a stream of samples with control 
% signals for input to the Simulink(R) model.

NDLRB=info.NDLRB;
if strcmp(enb.CyclicPrefix,'Normal')
    CPType=false;
else
    CPType=true;
end

sampling_time=1/30.72e6;
stoptime=enb.TotSubframes*(30720+4137+2048*2)*sampling_time;

idlecyclesbetweensamples = 0;
idlecyclesbetweenframes  = 0;

[dataIn,ctrl] = whdlFramesToSamples(mat2cell(LTEGrid(:),numel(LTEGrid),1),...
    idlecyclesbetweensamples,idlecyclesbetweenframes);
validIn = logical(ctrl(:,3));

%%
% Run the Simulink model.

modelname = 'OFDMModulatorModelExample';
open_system(modelname);
sim(modelname);

%%
% Save the output of the Simulink model and then compare the output of the 
% model against the output of the |lteOFDMModulate| function.

rxgridSimulink=dataOut(validOut);

figure('units','normalized','outerposition',[0 0 1 1])
subplot(2,1,1);
plot(real(eNodeBOutput));
hold on
plot(squeeze(real(rxgridSimulink)));
legend('Real part of behavioral waveform','Real part of HDL-optimized waveform');
title('Comparison of LTE Time-Domain Downlink Waveforms from Behavioral and HDL-Optimized Algorithms');
xlabel('OFDM subcarriers');
ylabel('Real part of the time-domain waveform');

subplot(2,1,2)
plot(imag(eNodeBOutput))
hold on
plot(squeeze(imag(rxgridSimulink)))
legend('Imag part of behavioral waveform','Imag part of HDL-optimized waveform');
title('Comparison of LTE Time-Domain Downlink Waveforms from Behavioral and HDL-Optimized Algorithms');
xlabel('OFDM subcarriers');
ylabel('Imag part of the time-domain waveform');
