0% found this document useful (0 votes)
10 views41 pages

Ex 2 - 8

Uploaded by

rohiniyuvaraj028
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views41 pages

Ex 2 - 8

Uploaded by

rohiniyuvaraj028
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Ex.

No:02 Modeling of 5G Synchronization signal blocks and bursts

Date :

Aim:

Software/Hardware Required:

⮚ MATLAB
⮚ Standalone Desktops

Theory:
It shows how to generate a synchronization signal block (SSB) and generate multiple
SSBs to form a synchronization signal burst (SS burst). The channels and signals that form
a synchronization signal block (primary and secondary synchronization signals, physical
broadcast channel) are created and mapped into a matrix representing the block. Finally a
matrix representing a synchronization signal burst is created, and each synchronization
signal block in the burst is created and mapped into the matrix.

TS 38.211 Section 7.4.3.1 defines the Synchronization Signal / Physical Broadcast Channel
(SS/PBCH) block as 240 subcarriers and 4 OFDM symbols containing the following channels
and signals:
● Primary synchronization signal (PSS)
● Secondary synchronization signal (SSS)
● Physical broadcast channel (PBCH)
● PBCH demodulation reference signal (PBCH DM-RS)

Program:
\\SS/PBCH block

ssblock = zeros([240 4])

\\Primary Synchronization Signal (PSS)

ncellid = 17;
pssSymbols = nrPSS(ncellid)
pssIndices = nrPSSIndices;
ssblock(pssIndices) = 1 * pssSymbols;
imagesc(abs(ssblock));
clim([0 4]);

axis xy;
xlabel('OFDM symbol');
ylabel('Subcarrier');
title('SS/PBCH block containing PSS');

\\Secondary Synchronization Signal (SSS)

sssSymbols = nrSSS(ncellid)
sssIndices = nrSSSIndices;
ssblock(sssIndices) = 2 * sssSymbols;
sssSubscripts =
nrSSSIndices('IndexStyle','subscript','IndexBase','0based')
imagesc(abs(ssblock));
clim([0 4]);
axis xy;
xlabel('OFDM symbol');
ylabel('Subcarrier');
title('SS/PBCH block containing PSS and SSS');

\\Physical Broadcast Channel (PBCH)

cw = randi([0 1],864,1);

\\Scrambling and modulation

v = 0;
pbchSymbols = nrPBCH(cw,ncellid,v)
pbchIndices = nrPBCHIndices(ncellid);
ssblock(pbchIndices) = 3 * pbchSymbols;
imagesc(abs(ssblock));
clim([0 4]);
axis xy;
xlabel('OFDM symbol');
ylabel('Subcarrier');
title('SS/PBCH block containing PSS, SSS and PBCH');

\\PBCH Demodulation Reference Signal

ibar_SSB = 0;
dmrsSymbols = nrPBCHDMRS(ncellid,ibar_SSB)
dmrsIndices = nrPBCHDMRSIndices(ncellid);
ssblock(dmrsIndices) = 4 * dmrsSymbols;
imagesc(abs(ssblock));
clim([0 4]);
axis xy;
xlabel('OFDM symbol');
ylabel('Subcarrier');
title('SS/PBCH block containing PSS, SSS, PBCH and PBCH DM-RS');

\\Generating an SS burst

nSubframes = 5
symbolsPerSlot = 14
mu = 1

\\Calculate the total number of OFDM symbols in an SS burst:

nSymbols = symbolsPerSlot * 2^mu * nSubframes

\\Create an empty grid for the whole SS burst

ssburst = zeros([240 nSymbols]);

\\Define SS block pattern

n = [0, 1];
firstSymbolIndex = [4; 8; 16; 20] + 28*n;
firstSymbolIndex = firstSymbolIndex(:).'

\\Create SS burst content

ssblock = zeros([240 4]);


ssblock(pssIndices) = pssSymbols;
ssblock(sssIndices) = 2 * sssSymbols;

forssbIndex = 1:length(firstSymbolIndex)

i_SSB = mod(ssbIndex - 1,8);


ibar_SSB = i_SSB;
v = i_SSB;

pbchSymbols = nrPBCH(cw,ncellid,v);
ssblock(pbchIndices) = 3 * pbchSymbols;

dmrsSymbols = nrPBCHDMRS(ncellid,ibar_SSB);
ssblock(dmrsIndices) = 4 * dmrsSymbols;

ssburst(:,firstSymbolIndex(ssbIndex) + (0:3)) = ssblock;

end

\\plot the SS burst content

imagesc(abs(ssburst));
clim([0 4]);
axis xy;
xlabel('OFDM symbol');
ylabel('Subcarrier');
title('SS burst, block pattern Case B');
OUTPUT:

Result:

Ex.No:03 Channel modeling in 5G networks

Date :

Aim:
Software/Hardware Required:

⮚ MATLAB
⮚ Standalone Desktops

Theory:
A channel model is a mathematical representation of the effects of a communication channel
through which wireless signals are propagated. The channel model can represent the power
loss incurred by the signal as it travels through the wireless medium. In a more general case,
the channel model is the impulse response of the channel medium in the time domain or its
Fourier transform in the frequency domain. The channel impulse response of a wireless
communication system typically varies randomly over time.

Channel models can be classified in four categories:

1. Path loss
2. Purely stochastic
3. Spatial
4. Ray tracing

Program:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
% Launcher Script
%
% This simulation is to
% 1. model MIMO channels by using the Mathworks 5G
NR CDL channel model in the 5G Toolbox;
% 2. estimate the average achievable channel
capacity, given different link lengths.
%
% Simulation assumptions
% 1. The path loss effect is included by default;
the shadow fading and oxygen absorption effects can be executed as
optional features [1].
% 2. The bandwidth scales linearly with the
carrier frequency.
% 3. For millimeter wave frequencies, the hybrid
precoding approach is adopted at both ends of the link [2].
%
% [1] 3GPP, "Study on channel model for frequencies from 0.5 to 100
GHz", 3rd Generation Partnership Project (3GPP), TR 38.901,
Dec.2017.
% [2] O.E.Ayach et al., "Spatially sparse precoding in millimeter
wave MIMO systems", Mar.2013.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
%% Simulation Parameters

clear variables; % Clear the workspace.

%%% Parameters for channel modelling

Fc = 30e9; % Carrier frequency in Hz


WaveLength = physconst('LightSpeed')/Fc;

BS_height = 25; % BS antenna height (macro-cell scenario)


UE_height = 1.5; % UE antenna height (outdoor UEs)

Dis2D = 50:50:300; % Horizontal BS-UE distance in meters


Dis3D = sqrt((BS_height-UE_height)^2+Dis2D.^2); % Actual BS-UE
distance

%%% Parameters for capacity calculation

BW = 0.005*Fc; % Bandwith in Hz
TX_power_mmWave = 35; % Transmit power in dBm, for mmWave
frequencies
TX_power_Microwave = 49; % Transmit power in dBm, for microwave
frequencies
Noise_power = -174; % dBm/Hz
Ns = 1; % Number of data streams
ITER = 1000; % Number of random channel realizations

%% Additional Channel Modelling Features

% Shadow fading
ShadowFadingFlag = 0; % 0 - not included, 1 - included
% Oxygen absorption
OxygenAbsorptionFlag = 0; % 0 - not included, 1 - included

%% CDL-A Channel Model

CDL_A = nrCDLChannel;

CDL_A.DelayProfile = 'CDL-A';
CDL_A.DelaySpread = 200*1e-9; % 200 ns
CDL_A.CarrierFrequency = Fc;
CDL_A.ChannelFiltering = false; % For extracting channel
coefficients

CDL_A.TransmitAntennaArray.Size = [4 4 1 1 1]; % [M N P Mg Ng]


CDL_A.TransmitAntennaArray.PolarizationAngles = [0,0]; % Default:
[45 -45], applies when P = 2
CDL_A.ReceiveAntennaArray.Size = [2 2 1 1 1]; % [M N P Mg Ng]
CDL_A.ReceiveAntennaArray.PolarizationAngles = [0,0]; % Default: [0
90], applies when P = 2

%% Channel Parameters Extraction

cdlinfo = info(CDL_A);

%%% Antenna configurations

% BS
Nt = cdlinfo.NumTransmitAntennas;
SizeBS = CDL_A.TransmitAntennaArray.Size; % Struct
ElementSpacingBS = CDL_A.TransmitAntennaArray.ElementSpacing; % [0.5
0.5 1 1]
% Obtain antenna position vectors using Phased Array System Toolbox
ArrayBS =
phased.URA('Size',SizeBS(1:2),'ElementSpacing',ElementSpacingBS(1:2)
*WaveLength);
ElePosBS = getElementPosition(ArrayBS); % 3 x (Nt/P), for one
polarization only
ElePosBS = repelem(ElePosBS,1,SizeBS(3)); % 3 x Nt

% UE
Nr = cdlinfo.NumReceiveAntennas;
SizeUE = CDL_A.ReceiveAntennaArray.Size; % Struct
ElementSpacingUE = CDL_A.ReceiveAntennaArray.ElementSpacing; % [0.5
0.5 0.5 0.5]
% Obtain antenna position vectors using Phased Array System Toolbox
ArrayUE =
phased.URA('Size',SizeUE(1:2),'ElementSpacing',ElementSpacingUE(1:2)
*WaveLength);
ElePosUE = getElementPosition(ArrayUE); % 3 x (Nr/P), for one
polarization only
ElePosUE = repelem(ElePosUE,1,SizeUE(3)); % 3 x Nr

%%% Clustered angles (AOD,AOA,ZOD,ZOA)

NumCluster = length(cdlinfo.PathDelays); % N

% Cluster angles
ClusterAOD = cdlinfo.AnglesAoD; % 1 x N
ClusterAOA = cdlinfo.AnglesAoA;
ClusterZOD = cdlinfo.AnglesZoD;
ClusterZOA = cdlinfo.AnglesZoA;

% Subpath angles
RayOffset = [0.0447 0.1413 0.2492 0.3715 0.5129 0.6797 0.8844 1.1481
1.5195 2.1551];
RayOffset = [RayOffset;-RayOffset];
RayOffset = RayOffset(:);

NumSubPaths = length(RayOffset); % M

AngleSpreads = CDL_A.AngleSpreads;

C_ASD = AngleSpreads(1);
C_ASA = AngleSpreads(2);
C_ZSD = AngleSpreads(3);
C_ZSA = AngleSpreads(4);

% M x N
RayAOD =
repmat(ClusterAOD,NumSubPaths,1)+C_ASD*repmat(RayOffset,1,NumCluster
);
RayAOA =
repmat(ClusterAOA,NumSubPaths,1)+C_ASA*repmat(RayOffset,1,NumCluster
);
RayZOD =
repmat(ClusterZOD,NumSubPaths,1)+C_ZSD*repmat(RayOffset,1,NumCluster
);
RayZOA =
repmat(ClusterZOA,NumSubPaths,1)+C_ZSA*repmat(RayOffset,1,NumCluster
);

% Randomly couple the departure and arrival angles.


RayAOD = Coupling(RayAOD,NumSubPaths,NumCluster);
RayAOA = Coupling(RayAOA,NumSubPaths,NumCluster);
RayZOD = Coupling(RayZOD,NumSubPaths,NumCluster);
RayZOA = Coupling(RayZOA,NumSubPaths,NumCluster);

%%% Steering vectors of depature/arrival angles

[Ar,At] =
getSteeringVector(RayAOD(:),RayAOA(:),RayZOD(:),RayZOA(:),ElePosBS,E
lePosUE,WaveLength);

%% Capacity Estimation

% NLOS path loss model (optional model)


[PathLoss,ShaSTD] = getPathLossNLOS(Fc*1e-9,Dis3D); % dB, vector
if ShadowFadingFlag == 1
PathLoss = PathLoss+normrnd(0,ShaSTD);
end

Capacity = zeros(length(Dis2D),ITER);

for d = 1:length(Dis2D)

for i = 1:ITER

% Extract channel coefficients.


[PathGains,~] = CDL_A();
PathGains = squeeze(mean(PathGains,1)); % Averaging over channel
snapshots
ChannelMatrix = permute(PathGains,[3,2,1]); % Nr x Nt x N

% Apply path loss.


ChannelMatrixPL = 1/sqrt(10^(PathLoss(d)/10))*ChannelMatrix;

% Oxygen absorption feature


if OxygenAbsorptionFlag == 1
OxygenLoss = Oxygen_Absorption(Fc); % dB/km
OxygenLoss = OxygenLoss*(Dis3D(d)/1000); % dB/m

ChannelMatrixFinal = 1/sqrt(10^(OxygenLoss/10))*ChannelMatrixPL;
else

ChannelMatrixFinal = ChannelMatrixPL;

end

% Capacity calculation (assuming narrowband channels)


NarrowbandChannels = sum(ChannelMatrixFinal,3);

if floor(Fc*1e-9) < 30 % Microwave frequencies

% MIMO multiplexing
Capacity(d,i) =
MIMO_Multiplexing(NarrowbandChannels,Ns,Noise_power,BW,TX_power_Micr
owave); % bits/s

else % Millimeter wave frequencies

% Hybrid precoding
Capacity(d,i) =
MIMO_HybridPrecoding(NarrowbandChannels,At,Ar,BW,TX_power_mmWave,Noi
se_power,Ns); % bits/s

end
end
end

AveCapacity = mean(Capacity,2)*1e-6; % Mbps

%% Capacity Plot

figure();title('Average Channel Capacity on CDL-A Model');


plot(Dis2D,AveCapacity,'-o','LineWidth',2.0,'MarkerSize',8.0);
xlabel('BS-UE Horizontal Distance (meter)');
ylabel('Average Capacity (Mbps)');
grid on;

function Angles_ray = Coupling(Angles_ray_temp,M,N)


%Randomly coupling depature and arrival subpath angles within one
clusters
%
%Input
% Angles_ray_temp : M x N
% M : number of subpaths
% N : number of clusters
%Output
% Angles_ray : M x N
%
[~,order] = sort(rand(M,N),1);
index = order+repmat([1:M:M*N],M,1)-1;
Angles_ray_temp = Angles_ray_temp(index);
Angles_ray = reshape(Angles_ray_temp,M,N);
end

function [PathLossNLOS,ShaNLOS] = getPathLossNLOS(Fc_GHz,Dis3D)


%%% NLOS path model in TR 38.901 (optional model)
% Input
% Fc_GHz : carrier frequency in GHz
% Dis3D : 3D BS-UE distance, 1 x
the number of NLOS links
% Output
% PathLossLOS : 1 x the number of NLOS links
% ShaNLOS : NLOS shadow fading std in dB
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

PathLossNLOS = 32.4+20*log10(Fc_GHz)+30*log10(Dis3D);
ShaNLOS = 7.8; % dB

End

function [Ar,At] =
getSteeringVector(RayAOD,RayAOA,RayZOD,RayZOA,ElePosBS,ElePosUE,Wave
Length)
% Obtain the array response vectors at the BS and UE for all
propagation angles.

% RayAOD/AOA/ZOD/ZOA: MN x 1
% ElePosBS/UE: 3 x Nt/Nr
% 3 x MN
UnitVectorBS = SphericalUnitVector(RayZOD,RayAOD);
UnitVectorUE = SphericalUnitVector(RayZOA,RayAOA);

% Steering vectors at BS and UE


At = exp(1i*2*pi*UnitVectorBS.'*ElePosBS/WaveLength); % MN x Nt
At = At.'; % Nt x MN
Ar = exp(1i*2*pi*UnitVectorUE.'*ElePosUE/WaveLength); % MN x Nr
Ar = Ar.'; % Nr x MN

function Capacity =
MIMO_HybridPrecoding(H,At,Ar,BW,TX_power_mmWave,Noise_power,Ns)
%%% This is the function to calculate the channel capacity for
millimeter wave signals.
%%% The hybrid precoding algorithms are proposed in [1].
%
% Input
% H : narrowband channel matrix, Nr x Nt
% At/Ar : the collection matrix of steering vectors of
BS/UE, Nt/Nr x MN
% BW : Hz
% TX_power_mmWave : dBm
% Noise_power : dBm/Hz
% Ns : number of data streams, 1
% Ouput
% Capacity : capacity in bits/s
%
% [1] O. E. Ayach et al.,"Spatially sparse precoding in millimeter
wave MIMO systems," Mar. 2013.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Number of RF chains = Number of data streams


NumRF = Ns;

Nr = size(Ar,1);

TX_power_mmWave = 10^(TX_power_mmWave/10)*1e-3; % watt


Noise_power = 10^(0.1*Noise_power)*1e-3; % watt/Hz
%%% Optimal precoder

% Singular value decomposition of the channel


[~,~,V] = svd(H);

% Optimal precoder
F_Opt = V(:,1:Ns); % Nt x Ns

%%% Hybrid precoding at the BS (Algorithm 1)

F_RF = [];
F_Res = F_Opt;
for r = 1:NumRF
Psi = At'*F_Res; % MN x Ns
[~,k] = max(diag(Psi*Psi')); % MN x MN
F_RF = [F_RF At(:,k)];
F_BB = (F_RF'*F_RF)\(F_RF'*F_Opt);
F_Res = (F_Opt-F_RF*F_BB)/norm(F_Opt-F_RF*F_BB,'fro');
end
F_BB = sqrt(Ns)*(F_BB/norm(F_RF*F_BB,'fro'));

%%% Hybrid combining at the UE (Algorithm 2)

% Covariance matrix of the receive symbols at the receive antennas


CovRx =
(TX_power_mmWave/Ns)*H*F_RF*F_BB*F_BB'*F_RF'*H'+Noise_power*eye(Nr);
% Nr x Nr

% Optimal unconstrained MMSE combiner without the hardware


limitation
W_MMSE = ((1/sqrt(TX_power_mmWave))*(F_BB'*F_RF'*H'*H*F_RF*F_BB+
((Noise_power*Ns)/TX_power_mmWave)*eye(Ns))\(F_BB'*F_RF'*H'))';

W_RF = [];
W_Res = W_MMSE;
for r = 1:NumRF
Psi = Ar'*CovRx*W_Res;
[~,k] = max(diag(Psi*Psi'));
W_RF = [W_RF Ar(:,k)];
W_BB = (W_RF'*CovRx*W_RF)\(W_RF'*CovRx*W_MMSE);
W_Res = (W_MMSE-W_RF*W_BB)/norm(W_MMSE-W_RF*W_BB,'fro');
end

%%% Capacity calculation

% Noise pwoer across the whole bandwidth


Rn = BW*Noise_power*W_BB'*W_RF'*W_RF*W_BB;

% Capacity in bits/s
Capacity = BW*abs(log2(det(eye(Ns)+(TX_power_mmWave/Ns)*(Rn\
(W_BB'*W_RF'*H*F_RF*F_BB*F_BB'*F_RF'*H'*W_RF*W_BB)))));

function Capacity =
MIMO_Multiplexing(H,Ns,Noise_power,BW,TX_power_Microwave)
%%% This is the function to calculate channel capacity by
multiplexing for microwave signals.
% Input
% H : narrowband channel matrix, Nr x Nt
% Ns : number of data streams, 1
% Noise_power : dBm/Hz
% BW : Hz
% TX_power_Microwave : dBm
% Ouput
% Capacity : capacity in bits/s
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

TX_power_Microwave = 10^(TX_power_Microwave/10)*1e-3; % watt


Noise_power = 10^(0.1*Noise_power)*1e-3; % watt/Hz

% Covariance matrix of transmitted symbols


CovTx = eye(Ns)*(1/Ns)*TX_power_Microwave;

% Noise power across the whole bandwidth


Rn = BW*Noise_power;

% Capacity calculation, bits/s


Capacity = BW*abs(log2(det(eye(Ns)+Rn\(H*CovTx*H'))));

function UnitVector = SphericalUnitVector(theta,phi)

% theta: P x 1
% phi : P x 1

UnitVector = [sind(theta.').*cosd(phi.');...
sind(theta.').*sind(phi.');...
cosd(theta.')]; % 3 x P

end

OUTPUT:
Result:

Ex.No:04 Multiband OFDM demodulation

Date :

Aim:

Software/Hardware Required:
⮚ MATLAB
⮚ Standalone Desktops

Program:
% MB-OFDM System simulation
clear all
close all
clc
% Configurable parameters
% Source length represents the number bits in input binary sequence
% it should be a multiple of 'BITS_PER_SYMBOL' otherwise zeros should be
% padded to the source.
SOURCE_LENGTH = 1200;
BINARY_ALPHABETS = [0,1];
% Create random binary source
randomData = randsrc(1,SOURCE_LENGTH,BINARY_ALPHABETS);
% Scramble the source using the ECMA-368 recommended scrambler
scrambledData = scramble(randomData,1);
% Do Convolutional encoding and puncturing to obtain encoded bits
encodedData = convEncode(scrambledData);
% Do Interleaving of the encoded data to circumvent burst errors
% Parameters for interleaving obtained from ECMA-368 standard for MB-OFDM
BITS_PER_SYMBOL = 100; % Number of bits per OFDM symbol
TDS_FACTOR = 2;
BLOCK_SIZE = 10;
CYCLIC_SHIFT = 33;
% Symbol interleaving
sIntrlvData = symbolIntrlv(encodedData,TDS_FACTOR,BITS_PER_SYMBOL);
% Tone interleaving
tIntrlvData = toneIntrlv(sIntrlvData,BLOCK_SIZE,BITS_PER_SYMBOL);
% Cyclic interleaving
cIntrlvData = cyclicIntrlv(tIntrlvData,CYCLIC_SHIFT,BITS_PER_SYMBOL);
% Modulate interleaved data using QPSK modulation
modData = modulateQPSK(cIntrlvData);
% Add guard and pilot sub carriers
mappedData = mapCarriers(modData);
% Take 128-point IDFT using IFFT algorithm
transmitSignal = ifft(reshape(mappedData,[],128),128,2);
% Reshape the matrix into a vector
txSignal = reshape(transmitSignal,1,[]);
% Plot the baseband tx signal
figure('Name','Transmitted Signal');
plot(abs(txSignal));
xlabel('Time');
ylabel('Amplitude');
title('MB-OFDM tx baseband signal');

function [codedBitVector] = convEncode(inputBitVector)


% Convolutionally encodes input data using ECMA standard for MB-OFDM system
% codedBits = convEncoder(inputBits)
% Encodes the inputBits convolutionally to obtain the codedBits.
%
% By ECMA standard the parameters of convolutional encoder are
% Constraint length = 7,
% Code rate = 1/3,
% Generator polynomial G0 = 133, G1 = 165, G2 = 171,
% Punctured code rate 1/2;
% Constraint length
L = 7;
% Generator polynomials for the three output bits of every input bit
G0 = 133;
G1 = 165;
G2 = 171;
% Puncture pattern for reducing the code rate from 1/3 to 1/2
PUNCTURE_PATTERN = [1,0,1];
% Create trellis structure that represents the convolutional code
convCodeTrellis = poly2trellis(L,[G0,G1,G2]);
% Do convolutional encoding with puncturing to obtain encoded bits
codedBitVector = convenc(inputBitVector,convCodeTrellis,PUNCTURE_PATTERN);
function [interleavedBits] = cyclicIntrlv(inputBits,shift,bitsPerSymbol)
% Does intra-symbol cyclic shifts
% interleavedBits = cyclicIntrlv(shift,bitsPerSymbol)
%
% 'interleavedBits' - Bits which are shifted for each block of
% 'bitsPerSymbol'.
% 'inputBits' - Bits which are coded and tone interleaved.
%` 'shift' - N(cyc) shift value to be used for cyclic shift.
% 'bitsPerSymbol' - Number of bits per OFDM symbol.
% Check 'shift' value
if (shift ~= 33) && (shift ~= 66)
error('Invalid shift value for cyclic interleaving');
end
% Check 'bitsPerSymbol' value
if (bitsPerSymbol ~= 100) && (bitsPerSymbol ~= 200)
error('Invalid number of bits per OFDM symbol');
end
% Check size of 'inputsBits' for a multiple of 'bitsPerSymbol'
if (mod(size(inputBits),bitsPerSymbol) ~= 0)
error('Incompatible size of coded bits vector');
end
% Create permute matrix for symbol interleaving
permuteMatrix = zeros(1,(6*bitsPerSymbol));
for i=0:(length(permuteMatrix)-1)
m = floor(i/bitsPerSymbol);
permuteMatrix(i+1) = ((m)*bitsPerSymbol+ mod(i + m * shift,bitsPerSymbol)) +
1;
end
interleavedBits = zeros(size(inputBits));
% Do cyclic block by block over the input bits
for i=1:(length(inputBits)/length(permuteMatrix))
offset = (i-1)*length(permuteMatrix);
interleavedBits(offset + 1 : offset + length(permuteMatrix)) =
intrlv(inputBits(offset + 1 : offset + length(permuteMatrix)),permuteMatrix);
end
function [outputVector] = mapCarriers(symbolVector)
% Maps symbols to data carriers, guard carriers and pilot carriers for
% MB-OFDM system
% Number of data sub carriers
Nd = 100;
% Number of guard sub carriers
Ng = 10;
% Number of pilot sub carriers
Np = 12;
% Check the number of symbols in 'symbolVector'
if(mod(length(symbolVector),Nd) ~= 0)
error('Invalid number of symbols');
end
outputVector = zeros(1,128*(numel(symbolVector)/Nd));
for i=1:(numel(symbolVector))/Nd
Cd = symbolVector(i:(i+Nd));
Cg = [Cd(1:Ng/2),Cd(Nd-(Ng/2)+1:Nd)];
Cp = modulateQPSK(ones(1,2*Np));

outputSymbols = zeros(1,128);
% Map the data, guard and pilot carriers
outputSymbols(68:128) = [ Cg(1:5), Cd(1), Cp(1), Cd(2:10), Cp(2), Cd(11:19),
Cp(3), Cd(20:28), Cp(4), Cd(29:37), Cp(5), Cd(38:46), Cp(6), Cd(47:50) ];
outputSymbols(1) = 0;
outputSymbols(2:62) = [ Cd(51:54), Cp(7), Cd(55:63), Cp(8), Cd(64:72), Cp(9),
Cd(73:81), Cp(10), Cd(82:90), Cp(11), Cd(91:99), Cp(12), Cd(100), Cg(6:10) ];
outputSymbols(63:67) = 0;

offset = (i-1)*128 + 1;
outputVector(offset:offset+127) = outputSymbols;
end
function [modulatedVector] = modulateQPSK(inputBitVector)
% QPSK modulator for MB-OFDM system recommended by ECMA standard
% modulatedVector = modulateQPSK(inputBitVector)
%
% 'inputBitVector' - Input bit stream
% 'modulatedVector' - complex value array representing the QPSK
% modulated symbols of the input bit stream
%
% QPSK modulation is carried out by grouping two consecutive bits in the
% 'inputBitVector' to form symbols which are then mapped to complex
% baseband representation of QPSK modulated symbols.
% check number of bits in inputBitVector; if odd pad it with zero
if(mod(length(inputBitVector),2) ~= 0)
lastBit = inputBitVector(end);
inputBitVector(end) = 0;
inputBitVector = [inputBitVector,lastBit];
end
% Construct QPSK object with symbol mapping recommended by ECMA
qpskModulator = modem.pskmod('M',4, ...
'PhaseOffset',5*pi/4, ...
'SymbolOrder','user-defined', ...
'SymbolMapping',[0,2,3,1], ...
'InputType','bit');
% Modulate input bit stream using QPSK
modulatedVector = modulate(qpskModulator,inputBitVector');
% Make modulatedVector as a row vector
modulatedVector = reshape(modulatedVector,1,[]);
function [scrambledBitVector] = scramble(inputBitVector, seedIdentifier)
% Scrambler for MB-OFDM system recommended by ECMA standard
% scrambledBitVector = scramble(inputBitVector, seedIdentifier)
% This function scrambles the 'inputBitVector' based on the recommended
% standard by ECMA for MB-OFDM system. 'seedIdentifier' is used to
% determine one among the four initial values for the LFSR.
%
% Note: 'seedIdentifier' takes only 1,2,3 or 4;
% Check value of seedIdentifier
if (seedIdentifier< 1) || (seedIdentifier> 4)
error('Invalid seed identifier given');
end
SEED = [[0,0,1,1, 1,1,1,1, 1,1,1,1, 1,1,1]
[0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1]
[1,0,1,1, 1,1,1,1, 1,1,1,1, 1,1,1]
[1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1]];
% Get initial state from the give seed identifier
initialState = SEED(ceil(seedIdentifier),:);
% Generator polynomial for LFSR ( 1 + x^(-14) + x^(-15) )
generatorPolynomial = [1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,1,1];
% Mask represents the value to tap from LFSR as output
mask = [1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0];
% Create PN Sequence object having the recommended generator polynomial and
% given initialState
h = seqgen.pn('GenPoly',generatorPolynomial, ...
'InitialStates',initialState, ...
'CurrentStates',initialState, ...
'Mask',mask, ...
'NumBitsOut',1);
% Number of bits to generate for scrambling must be equal to the number of
% bits in the input
set(h,'NumBitsOut',numel(inputBitVector));
% Do bitwise xor between input bits and generated pseudo-random bits to get
% the scrambled output bits
scrambledBitVector = bitxor(inputBitVector,reshape(generate(h),1,[]));
function [interleavedBits] = symbolIntrlv(codedBits,tdsFactor,bitsPerSymbol)
% Interleaves the coded bits across 6 OFDM symbols
% interleavedBits = symbolIntrlv(codedBits,tdsFactor,bitsPerSymbol)
%
% 'interleavedBits' - Bits which are interleaved among 6 OFDM symbols
% 'codedBits' - Bits which are coded using FEC.
% 'tdsFactor' - N(TDS), time division spreading value (1 or 2)
% 'bitsPerSymbol' - N(CBPS) number of coded bits per OFDM symbol.
%
% Symbol interleaving is done by grouping the 'codedBits' into blocks of
% 6 X 'bitsPerSymbol' and then permuting it.
% Check 'tdsFactor' value
if (tdsFactor> 2) || (tdsFactor< 1)
error('Invalid TDS factor !');
end
% Check 'bitsPerSymbol' value
if (bitsPerSymbol ~= 100) && (bitsPerSymbol ~= 200)
error('Invalid number of bits per OFDM symbol');
end
% Check size of coded bits for a multiple of (6*(bitsPerSymbol))
if (mod(size(codedBits),6*(bitsPerSymbol)) ~= 0)
error('Incompatible size of coded bits vector');
end
% Create permute matrix for symbol interleaving
permuteMatrix = zeros(1,(6*bitsPerSymbol)/tdsFactor);
for i=0:(length(permuteMatrix)-1)
permuteMatrix(i+1) = (floor(i/bitsPerSymbol) + ((6/tdsFactor) *
mod(i,bitsPerSymbol))) + 1;
end
interleavedBits = zeros(size(codedBits));
% Do interleaving block by block over the coded bits
for i=1:(length(codedBits)/length(permuteMatrix))
offset = (i-1)*length(permuteMatrix);
interleavedBits(offset + 1 : offset + length(permuteMatrix)) =
intrlv(codedBits(offset + 1 : offset + length(permuteMatrix)),permuteMatrix);
end
function [interleavedBits] = toneIntrlv(inputBits,blockSize,bitsPerSymbol)
% Tone interleaving permutes coded bits across the data subcarries
% with in an OFDM symbol
% interleavedBits = toneIntrlv(codedBits,blockSize)
%
% 'interleavedBits' - Bits which are interleaved among data subcarries of
% each OFDM symbol.
% 'inputBits' - Bits which are coded and symbol interleaved.
% 'blockSize' - Block size provided by ECMA standard for tone
% interleaving, (10 or 20)
% 'bitsPerSymbol' - Number of bits per OFDM symbol.
% Check 'blockSize' value
if (blockSize ~= 10) && (blockSize ~= 20)
error('Invalid block size for tone interleaving');
end
% Check 'bitsPerSymbol' value
if (bitsPerSymbol ~= 100) && (bitsPerSymbol ~= 200)
error('Invalid number of bits per OFDM symbol');
end
% Check size of 'inputsBits' for a multiple of 'bitsPerSymbol'
if (mod(size(inputBits),bitsPerSymbol) ~= 0)
error('Incompatible size of coded bits vector');
end
% Create permute matrix for tone interleaving
permuteMatrix = zeros(1,(10*blockSize));
for i=0:(length(permuteMatrix)-1)
permuteMatrix(i+1) = (floor(i/blockSize) + (10 * mod(i,blockSize))) + 1;
end
interleavedBits = zeros(size(inputBits));
% Do interleaving block by block with block size as one OFDM symbol
for i=1:(length(inputBits)/length(permuteMatrix))
offset = (i-1)*length(permuteMatrix);
interleavedBits(offset + 1 : offset + length(permuteMatrix)) =
intrlv(inputBits(offset + 1 : offset + length(permuteMatrix)),permuteMatrix);
end
OUTPUT:
Result:

Ex.No:05 Perfect Channel estimation

Date :

Aim:

Software/Hardware Required:

⮚ MATLAB
⮚ Standalone Desktops
Program:
% simulation for channel estimation techniequs using LS, LMMMSE, and
% computationally efficient LMMMSE methods.
% Prepared by: Hiren Gami
% Ref: J J Van de Beek, "Synchronization and Channel Estimation in OFDM
% systems", Ph.Dthesis,Sept. 1998
clc
clear all
nCP = 8;%round(Tcp/Ts);
nFFT = 64;
NT = nFFT + nCP;
F = dftmtx(nFFT)/sqrt(nFFT);
MC = 1500;
EsNodB = 0:5:40;
snr = 10.^(EsNodB/10);
beta = 17/9;
M = 16;
modObj = modem.qammod(M);
demodObj = modem.qamdemod(M);
L = 5;
ChEstLS = zeros(1,length(EsNodB));
ChEstMMSE = zeros(1,length(EsNodB));
TD_ChEstMMSE = zeros(1,length(EsNodB));
TDD_ChEstMMSE = zeros(1,length(EsNodB));
TDQabs_ChEstMMSE = zeros(1,length(EsNodB));
for ii = 1:length(EsNodB)
disp('EsN0dB is :'); disp(EsNodB(ii));tic;
ChMSE_LS = 0;
ChMSE_LMMSE=0;
TDMSE_LMMSE =0;
TDDMSE_LMMSE=0;
TDQabsMSE_LMMSE =0;
for mc = 1:MC
% Random channel taps
g = randn(L,1)+1i*randn(L,1);
g = g/norm(g);
H = fft(g,nFFT);
% generation of symbol
X = randi([0 M-1],nFFT,1); %BPSK symbols
XD = modulate(modObj,X)/sqrt(10); % normalizing symbol power
x = F'*XD;
xout = [x(nFFT-nCP+1:nFFT);x];
% channel convolution and AWGN
y = conv(xout,g);
nt =randn(nFFT+nCP+L-1,1) + 1i*randn(nFFT+nCP+L-1,1);
No = 10^(-EsNodB(ii)/10);
y = y + sqrt(No/2)*nt;
% Receiver processing
y = y(nCP+1:NT);
Y = F*y;
% frequency doimain LS channel estimation
HhatLS = Y./XD;
ChMSE_LS = ChMSE_LS + ((H -HhatLS)'*(H-HhatLS))/nFFT;
% Frequency domain LMMSE estimation
Rhh = H*H';
W = Rhh/(Rhh+(beta/snr(ii))*eye(nFFT));
HhatLMMSE = W*HhatLS;
ChMSE_LMMSE = ChMSE_LMMSE + ((H -HhatLMMSE)'*(H-HhatLMMSE))/nFFT;
% Time domain LMMSE estimation
ghatLS = ifft(HhatLS,nFFT);
Rgg = g*g';
WW = Rgg/(Rgg+(beta/snr(ii))*eye(L));
ghat = WW*ghatLS(1:L);
TD_HhatLMMSE = fft(ghat,nFFT);%
TDMSE_LMMSE = TDMSE_LMMSE + ((H
-TD_HhatLMMSE)'*(H-TD_HhatLMMSE))/nFFT;
% Time domain LMMSE estimation - ignoring channel covariance
ghatLS = ifft(HhatLS,nFFT);
Rgg = diag(g.*conj(g));
WW = Rgg/(Rgg+(beta/snr(ii))*eye(L));
ghat = WW*ghatLS(1:L);
TDD_HhatLMMSE = fft(ghat,nFFT);%
TDDMSE_LMMSE = TDDMSE_LMMSE + ((H -TDD_HhatLMMSE)'*(H-
TDD_HhatLMMSE))/nFFT;

% Time domain LMMSE estimation - ignoring smoothing matrix


ghatLS = ifft(HhatLS,nFFT);
TDQabs_HhatLMMSE = fft(ghat,nFFT);%
TDQabsMSE_LMMSE = TDQabsMSE_LMMSE + ((H -TDQabs_HhatLMMSE)'*(H-
TDQabs_HhatLMMSE))/nFFT;

end
ChEstLS(ii) = ChMSE_LS/MC;
ChEstMMSE(ii)=ChMSE_LMMSE/MC;
TD_ChEstMMSE(ii)=TDMSE_LMMSE/MC;
TDD_ChEstMMSE(ii)=TDMSE_LMMSE/MC;
TDQabs_ChEstMMSE(ii)=TDQabsMSE_LMMSE/MC;
toc;
end
% Channel estimation
semilogy(EsNodB,ChEstLS,'r','LineWidth',2);
hold on;gridon;xlabel('EsNodB'); ylabel('Channel MSE');
semilogy(EsNodB,ChEstMMSE,'k','LineWidth',2);
semilogy(EsNodB,TD_ChEstMMSE,'g','LineWidth',2);
semilogy(EsNodB,TDD_ChEstMMSE,'m','LineWidth',2);
semilogy(EsNodB,TDQabs_ChEstMMSE,'b','LineWidth',2);
% Theoratical bound calculation
semilogy(EsNodB,beta./snr,'-.r*','LineWidth',2);
ThLMMSE = (1/nFFT)*(beta./snr).*(1./(1+(beta./snr)));
semilogy(EsNodB,ThLMMSE,'-.k*','LineWidth',2);
legend('LS','MMSE', 'TD LMMSE','TDD LMMSE','TD QabsLMMSE','Theory-LS',
'Theory-LMMSE');
OUTPUT:
Result:

Ex.No:06 Development of 5G New Radio Polar Coding

Date :

Aim:

Software/Hardware Required:

⮚ MATLAB
⮚ Standalone Desktops

Program:

s = rng(100); % Seed the RNG for repeatability


% Code parameters
K = 54; % Message length in bits, including CRC, K > 30
E = 124; % Rate matched output length, E <= 8192

EbNo = 0.8; % EbNo in dB


L = 8; % List length, a power of two, [1 2 4 8]
numFrames = 10; % Number of frames to simulate
linkDir = 'DL'; % Link direction: downlink ('DL') OR uplink ('UL')
ifstrcmpi(linkDir,'DL')
% Downlink scenario (K >= 36, including CRC bits)
crcLen = 24; % Number of CRC bits for DL, Section 5.1, [6]
poly = '24C'; % CRC polynomial
nPC = 0; % Number of parity check bits, Section 5.3.1.2, [6]
nMax = 9; % Maximum value of n, for 2^n, Section 7.3.3, [6]
iIL = true; % Interleave input, Section 5.3.1.1, [6]
iBIL = false; % Interleave coded bits, Section 5.4.1.3, [6]
else
% Uplink scenario (K > 30, including CRC bits)
crcLen = 11;
poly = '11';
nPC = 0;
nMax = 10;
iIL = false;
iBIL = true;
end
R = K/E; % Effective code rate
bps = 2; % bits per symbol, 1 for BPSK, 2 for QPSK
EsNo = EbNo + 10*log10(bps);
snrdB = EsNo + 10*log10(R); % in dB
noiseVar = 1./(10.^(snrdB/10));

% Channel
chan = comm.AWGNChannel('NoiseMethod','Variance','Variance',noiseVar);
% Error meter
ber = comm.ErrorRate;
numferr = 0;
fori = 1:numFrames

% Generate a random message


msg = randi([0 1],K-crcLen,1);

% Attach CRC
msgcrc = nrCRCEncode(msg,poly);

% Polar encode
encOut = nrPolarEncode(msgcrc,E,nMax,iIL);
N = length(encOut);

% Rate match
modIn = nrRateMatchPolar(encOut,K,E,iBIL);

% Modulate
modOut = nrSymbolModulate(modIn,'QPSK');

% Add White Gaussian noise


rSig = chan(modOut);

% Soft demodulate
rxLLR = nrSymbolDemodulate(rSig,'QPSK',noiseVar);

% Rate recover
decIn = nrRateRecoverPolar(rxLLR,K,N,iBIL);

% Polar decode
decBits = nrPolarDecode(decIn,K,E,L,nMax,iIL,crcLen);

% Compare msg and decoded bits


errStats = ber(double(decBits(1:K-crcLen)), msg);
numferr = numferr + any(decBits(1:K-crcLen)~=msg);

end

disp(['Block Error Rate: ' num2str(numferr/numFrames) ...


', Bit Error Rate: ' num2str(errStats(1)) ...
', at SNR = ' num2str(snrdB) ' dB'])

rng(s); % Restore RNG

OUTPUT:
Result:

Ex.No:07 6G Link level Simulation

Date :

Aim:

To simulate 6G waveform using MATLAB

Software/Hardware Required:

⮚ MATLAB
⮚ Standalone Desktops

Program:

simParameters = struct(); % Simulation parameters structure


simParameters.NFrames = 2; % Number of 10 ms frames
simParameters.SNRdB = -10:2:-6; % SNR range (dB)

simParameters.enableParallelism = true;

simParameters.PerfectChannelEstimator = false;

simParameters.DisplaySimulationInformation = true;

simParameters.DisplayDiagnostics = false;

% Set carrier parameters


simParameters.Carrier = pre6GCarrierConfig; %
Carrier resource grid configuration
simParameters.Carrier.NSizeGrid = 330; %
Bandwidth in number of resource blocks
simParameters.Carrier.SubcarrierSpacing = 120; %
Subcarrier spacing

% Set PDSCH parameters


simParameters.PDSCH = pre6GPDSCHConfig; % PDSCH
definition for all PDSCH transmissions in the BLER simulation
% Define PDSCH time-frequency resource allocation per slot to be full grid
(single full grid BWP) and number of layers
simParameters.PDSCH.PRBSet = 0:simParameters.Carrier.NSizeGrid-1;
% PDSCH PRB allocation
simParameters.PDSCH.SymbolAllocation =
[0,simParameters.Carrier.SymbolsPerSlot]; % Starting symbol and number of
symbols of each PDSCH allocation
simParameters.PDSCH.NumLayers = 1;
% Number of PDSCH transmission layers

% This structure is to hold additional simulation parameters for the DL-


SCH and PDSCH
simParameters.PDSCHExtension = struct();

% Define codeword modulation and target coding rate


% The number of codewords is directly dependent on the number of layers so
ensure that layers are set first before getting the codeword number
if simParameters.PDSCH.NumCodewords> 1 %
Multicodeword transmission (when number of layers is > 4)
simParameters.PDSCH.Modulation = {'16QAM','16QAM'}; % 'QPSK',
'16QAM', '64QAM', '256QAM', '1024QAM'
simParameters.PDSCHExtension.TargetCodeRate = [490 490]/1024; % Code rate
used to calculate transport block sizes
else
simParameters.PDSCH.Modulation = '16QAM'; % 'QPSK',
'16QAM', '64QAM', '256QAM', '1024QAM'
simParameters.PDSCHExtension.TargetCodeRate = 490/1024; % Code rate
used to calculate transport block sizes
end

% Disable PT-RS
simParameters.PDSCH.EnablePTRS = false;

% PDSCH PRB bundling (TS 38.214 Section 5.1.2.3)


simParameters.PDSCHExtension.PRGBundleSize = []; % Any
positive power of 2, or [] to signify "wideband"

% HARQ process parameters


simParameters.PDSCHExtension.NHARQProcesses = 16; % Number
of parallel HARQ processes to use
simParameters.PDSCHExtension.EnableHARQ = true; % Enable
retransmissions for each process, using RV sequence [0,2,3,1]

% LDPC decoder parameters


simParameters.PDSCHExtension.LDPCDecodingAlgorithm = 'Normalized min-sum';
simParameters.PDSCHExtension.MaximumLDPCIterationCount = 20;

% Number of antennas
simParameters.NTxAnts = 32; % Number
of antennas (1,2,4,8,16,32,64,128,256,512,1024) >= NumLayers
simParameters.NRxAnts = 2;

% Define the general CDL propagation channel parameters


simParameters.DelayProfile = 'CDL-A';
simParameters.DelaySpread = 10e-9;
simParameters.MaximumDopplerShift = 70;

% Cross-check the PDSCH layering against the channel geometry


validateNumLayers(simParameters);

if (simParameters.enableParallelism&&canUseParallelPool)
pool = gcp; % create parallel pool, requires PCT
numWorkers = pool.NumWorkers;
maxNumWorkers = pool.NumWorkers;
else
if (~canUseParallelPool&&simParameters.enableParallelism)
warning("Ignoring the value of
enableParallelism("+simParameters.enableParallelism+")"+newline+ ...
"The simulation will run using serial execution."+newline+"You
need a license of Parallel Computing Toolbox to use parallelism.")
end
numWorkers = 1; % No parallelism
maxNumWorkers = 0; % Used to convert the parfor-loop into a for-loop
end

str1 = RandStream('Threefry','Seed',1);
constantStream = parallel.pool.Constant(str1);

numSlotsPerWorker =
ceil((simParameters.NFrames*simParameters.Carrier.SlotsPerFrame)/numWorker
s);
disp("Parallelism: "+simParameters.enableParallelism)

disp("Number of workers: "+numWorkers)

disp("Number of slots per worker: "+numSlotsPerWorker)

disp("Total number of frames:


"+(numSlotsPerWorker*numWorkers)/simParameters.Carrier.SlotsPerFrame)

% Results storage
result = struct(NumSlots=0,NumBits=0,NumCorrectBits=0);
results = repmat(result,numWorkers,numel(simParameters.SNRdB));

% Parallel processing, worker parfor-loop


parfor (pforIdx = 1:numWorkers,maxNumWorkers)
% Set random streams to ensure repeatability
% Use substreams in the generator so each worker uses mutually
independent streams
stream = constantStream.Value; % Extract the stream from the
Constant
stream.Substream = pforIdx; % Set substream value = parfor index
RandStream.setGlobalStream(stream); % Set global stream per worker

% Per worker processing


results(pforIdx,:) = pdschLink(simParameters,numSlotsPerWorker,pforIdx);
end

OUTPUT:
Result:

Thus the simulation of 6G Waveform using MATLAB were executed Successfully.

Ex.No:08 Measure the impact of Sub-THz Hardware impairments on 6G


Waveforms

Date :

Aim:

To Measure the impact of Sub-THz Hardware impairments on 6G Waveformsusing


MATLAB

Software/Hardware Required:

⮚ MATLAB
⮚ Standalone Desktops

Program:

carrierFrequency = 140; % GHz


bandwidth = 2160; % MHz - transmission bandwidth and guardbands
subcarrierSpacing = 3840; % kHz

bandwidthOccupancy = 0.8; % Ratio of transmission bandwidth to channel


bandwidth

carrier = pre6GCarrierConfig;
carrier.SubcarrierSpacing = subcarrierSpacing;
channelBandwidth = bandwidth*1e6; % Bandwidth of RBs and guard carriers in
Hz
carrier.NSizeGrid =
floor((channelBandwidth/(carrier.SubcarrierSpacing*1e3)*bandwidthOccupancy
)/12); % 12 subcarriers per RB
transmissionBandwidth =
carrier.SubcarrierSpacing*1e3*carrier.NSizeGrid*12; % Bandwidth of RBs in
Hz

numSubframes = 0.5; % Number of subframes to simulate


tddConfig.TDDPeriod = 10; % TDD period in slots
tddConfig.NumDownlinkSlots = 9; % Number of slots in TDD period containing
PDSCH
numSlots = numSubframes*carrier.SlotsPerSubframe;
tddConfig.SlotAllocation = 0:tddConfig.NumDownlinkSlots-1; % Assume
downlink slots at start of TDD period
disp(join(["Simulating" num2str(numSlots) "slots"]))

visualizeTDDAllocation(tddConfig);

pdsch = pre6GPDSCHConfig;
pdsch.PRBSet = 0:(carrier.NSizeGrid-1);
pdsch.Modulation = "16QAM";
pdsch.EnablePTRS = true;

waveGrid = []; % Store resource grid to transmit


for nSlot = 0:(numSlots-1)
carrier.NSlot = nSlot;
slotGrid = hpre6GResourceGrid(carrier,pdsch.NumLayers);

% Generate content if slot allocated to PDSCH


if isSlotActive(carrier.NSlot,tddConfig)
[ind,indInfo] = hpre6GPDSCHIndices(carrier,pdsch);
% Generate and map PDSCH for a random codeword
cw = randi([0 1],indInfo.G,1);
sym = hpre6GPDSCH(carrier,pdsch,cw);
slotGrid(ind) = sym;

% Generate and map DMRS


dmrsInd = hpre6GPDSCHDMRSIndices(carrier,pdsch);
dmrsSym = hpre6GPDSCHDMRS(carrier,pdsch);
slotGrid(dmrsInd) = dmrsSym;

% Generate and map PT-RS


ptrsInd = hpre6GPDSCHPTRSIndices(carrier,pdsch);
ptrsSym = hpre6GPDSCHPTRS(carrier,pdsch);
slotGrid(ptrsInd) = ptrsSym;
end
waveGrid = [waveGridslotGrid];
end

% OFDM-modulate with specified oversampling factor


oversamplingFactor = 3; % Multiple of the channel bandwidth
carrier.NSlot = 0; % OFDM-modulate from slot 0
nFFTWaveform =
ceil((channelBandwidth/(carrier.SubcarrierSpacing*1e3))*oversamplingFactor
/128)*128;
[txWaveform,ofdmInfo] =
hpre6GOFDMModulate(carrier,waveGrid,Nfft=nFFTWaveform);

% Normalize waveform to maximum amplitude for PA modeling


txWaveform = txWaveform/max(abs(txWaveform),[],"all");
% Prepend slot to the waveform to allow to allow for filter delay
waveformLength = height(txWaveform);
slotLength = waveformLength/numSlots;
txWaveform = [txWaveform(end-slotLength+1:end,:); txWaveform];

enablePN = true; % Enable phase noise model


if enablePN
minimumFrequencyOffset = 1e6; % Hz
mdl = "HexaX Model 2";
phaseNoise =
hpre6GPhaseNoise(carrierFrequency*1e9,ofdmInfo.SampleRate, ...
MinFrequencyOffset=minimumFrequencyOffset,Model=mdl, ...
RandomStream="mt19937ar with seed");
visualize(phaseNoise); % Show phase noise PSD
rxWaveform = phaseNoise(txWaveform); % Apply phase noise model
else
rxWaveform = txWaveform; %#ok<UNRCH>
end

enableLPF = true; % Enable low-pass filter


if enableLPF
% Create low-pass filter object
LPF = dsp.LowpassFilter;
LPF.SampleRate = ofdmInfo.SampleRate;
LPF.FilterType = "IIR";
LPF.PassbandFrequency = (transmissionBandwidth +
24*carrier.SubcarrierSpacing*1e3)/2;
LPF.StopbandFrequency = channelBandwidth/2; % TransmissionBandwidth and
guards
LPF.PassbandRipple = 0.2;
LPF.StopbandAttenuation = 40;
figure;
freqz(LPF); % Plot the response of the low-pass filter

% Filter the waveform


rxWaveform = LPF(rxWaveform);
release(LPF);
end

enablePA = true; % Enable power amplifier model


if enablePA
backoff = 6; % In dB
rxWaveform = db2mag(-backoff)*rxWaveform; % Apply PA backoff
visualizeAMAMCharacteristic(@paMemorylessGaN,"GaN");

rxWaveform = paMemorylessGaN(rxWaveform);
end

measureACPR = true;
if measureACPR
% Calculate the number of adjacent channels which can be measured
given
% the sample rate
numAdjacentChannels = floor((ofdmInfo.SampleRate/channelBandwidth-1)/2);
if numAdjacentChannels>0
sa = spectrumAnalyzer;
sa.SampleRate = ofdmInfo.SampleRate;
sa.ChannelMeasurements.Type = "acpr";
sa.ChannelMeasurements.Enabled = true;
sa.ChannelMeasurements.Span = transmissionBandwidth;
sa.ChannelMeasurements.NumOffsets = numAdjacentChannels;
sa.ChannelMeasurements.AdjacentBW = transmissionBandwidth;
sa.ChannelMeasurements.ACPROffsets =
(1:numAdjacentChannels)*channelBandwidth;
sa(rxWaveform);
else
warning('Sample rate too low to measure ACPR, increase
oversamplingFactor')
end
end

Measure EVM
Perform the following steps to measure the EVM:
1. Synchronize the received waveform
2. OFDM-demodulate the received waveform
3. Perform channel estimation
4. Equalize the PDSCH symbols
5. Estimate and compensate the common phase error (CPE)
6. Compute PDSCH EVM
Show the equalized PDSCH symbols for each slot.

% Ignore transients in first part of waveform


rxWaveform(1:slotLength,:) = [];

% Timing synchronization
refSlotGrid = waveGrid(:,1:carrier.SymbolsPerSlot,:);
offset =
hpre6GTimingEstimate(carrier,rxWaveform,refSlotGrid,Nfft=ofdmInfo.Nfft);
rxWaveform = rxWaveform(1+offset:end,:);

% Demodulate and measure EVM of each slot


rxWaveGrid = hpre6GOFDMDemodulate(carrier,rxWaveform,Nfft=ofdmInfo.Nfft);

% Setup constellation diagram


constDiagram = comm.ConstellationDiagram;
constDiagram.ShowReferenceConstellation = true;

L = carrier.SymbolsPerSlot;
numRxSlots = floor(size(rxWaveGrid,2)/L);
if numRxSlots<1
error('Not enough data to measure EVM, increase numSubframes')
end
evGrid = []; % Store error vector for each resource element
evm = []; % Store EVM measurement for each slot containing PDSCH
for nSlot = 0:(numRxSlots-1)
carrier.NSlot = nSlot;
evSlotGrid = NaN*hpre6GResourceGrid(carrier,pdsch.NumLayers); % Store
error vector
if isSlotActive(nSlot,tddConfig)
% Extract slot from grid
rxSlotGrid = rxWaveGrid(:,nSlot*L+(1:L),:);

% Estimate channel
pdschDMRSInd = hpre6GPDSCHDMRSIndices(carrier,pdsch);
pdschDMRSSymbols = hpre6GPDSCHDMRS(carrier,pdsch);
[hest,nVar] =
hpre6GChannelEstimate(carrier,rxSlotGrid,pdschDMRSInd,pdschDMRSSymbols,CDM
Lengths=pdsch.DMRS.CDMLengths);

% Equalize PDSCH
[pdschInd,pdschIndInfo] = hpre6GPDSCHIndices(carrier,pdsch);
[pdschRxSym,pdschHest] =
nrExtractResources(pdschInd,rxSlotGrid,hest);
pdschEqSym = nrEqualizeMMSE(pdschRxSym,pdschHest,nVar);

% Correct common phase error


pdschEqSym =
correctCPE(carrier,pdsch,pdschInd,pdschIndInfo,rxSlotGrid,hest,nVar,pdschE
qSym);

% Demap, decode, and re-modulate to obtain layer demapped


equalized
% symbols (rxSym) and reference symbols (refSym) for EVM
% measurement.
[cw,rxSym] = hpre6GPDSCHDecode(carrier,pdsch,pdschEqSym,nVar);
expectedCW = cw{1}<0; % LLR<0 is bit 1, otherwise bit 0
expectedPDSCHSym = hpre6GPDSCH(carrier,pdsch,expectedCW);
[~,refSym] = hpre6GPDSCHDecode(carrier,pdsch,expectedPDSCHSym,0);

% Show equalized PDSCH constellation


constDiagram.ReferenceConstellation = unique(refSym{1});
constDiagram.Title = join(["Equalized PDSCH slot" num2str(nSlot)]);
constDiagram(rxSym{1});

% Calculate error vector and EVM


slotEVM = measureEVM(refSym{1},rxSym{1});
fprintf("Slot %d PDSCH EVM, RMS: %0.3f%% Peak: %0.3f%%\
n",nSlot,slotEVM.RMS*100,slotEVM.Peak*100);
evm = [evm slotEVM];

% Store error vector in grid


evSlotGrid = NaN(size(rxSlotGrid));
evSlotGrid(pdschInd) = slotEVM.EV;
end
evGrid = [evGridevSlotGrid]; %#ok<*AGROW>
end

OUTPUT:
Result:

Thusthe Measurement of the impact of Sub-THz Hardware impairments on 6G Waveforms


using MATLAB were executed Successfully.

You might also like