Communications System Toolbox™ Getting Started Guide R 2014b

Communications System Toolbox™
Getting Started Guide
R2014b
How to Contact MathWorks
Latest news:
www.mathworks.com
Sales and services:
www.mathworks.com/sales_and_services
User community:
www.mathworks.com/matlabcentral
Technical support:
www.mathworks.com/support/contact_us
Phone:
508-647-7000
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
Communications System Toolbox™ Getting Started Guide
© COPYRIGHT 2011–2014 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and
govern the use, modification, reproduction, release, performance, display, and disclosure of the Program
and Documentation by the federal government (or other entity acquiring for or through the federal
government) and shall supersede any conflicting contractual terms or conditions. If this License fails
to meet the government's needs or is inconsistent in any respect with federal procurement law, the
government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
April 2011
September 2011
March 2012
September 2012
March 2013
September 2013
March 2014
October 2014
First printing
Online only
Online only
Online only
Online only
Online only
Online only
Online only
New for Version 5.0 (Release 2011a)
Revised for Version 5.1 (Release 2011b)
Revised for Version 5.2 (Release 2012a)
Revised for Version 5.3 (Release 2012b)
Revised for Version 5.4 (Release 2013a)
Revised for Version 5.5 (Release 2013b)
Revised for Version 5.6 (Release 2014a)
Revised for Version 5.7 (Release 2014b)
Contents
1
2
Introduction
Communications System Toolbox Product Description . . . .
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2
1-2
System Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Required Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Expected Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Configure the Simulink Environment for Communications
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-3
1-3
1-3
Access the Block Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-5
Communications System Toolbox Supported Hardware . . .
1-6
1-3
System Simulation
256-QAM with Simulink Blocks . . . . . . . . . . . . . . . . . . . . . . . .
Section Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Opening the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overview of the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Quadrature Amplitude Modulation . . . . . . . . . . . . . . . . . . . .
Run a Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display the Error Rate . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Set Block Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display a Phase Noise Plot . . . . . . . . . . . . . . . . . . . . . . . . . .
2-2
2-2
2-2
2-3
2-4
2-5
2-6
2-7
2-9
16-QAM with MATLAB Functions . . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modulate a Random Signal . . . . . . . . . . . . . . . . . . . . . . . . .
2-11
2-11
2-11
iii
Plot Signal Constellations . . . . . . . . . . . . . . . . . . . . . . . . . .
Pulse Shaping Using a Raised Cosine Filter . . . . . . . . . . . .
Error Correction using a Convolutional Code . . . . . . . . . . .
2-18
2-22
2-29
Iterative Design Workflow for Communication Systems . .
Simulate a basic communications system . . . . . . . . . . . . . .
Introduce convolutional coding and hard-decision Viterbi
decoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Improve results using soft-decision decoding . . . . . . . . . . . .
Use turbo coding to improve BER performance . . . . . . . . . .
Apply a Rayleigh channel model . . . . . . . . . . . . . . . . . . . . .
Use OFDM-based equalization to correct multipath fading .
Use multiple antennas to further improve system
performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accelerate the simulation using MATLAB Coder . . . . . . . . .
2-33
2-34
2-38
2-42
2-47
2-50
2-55
QPSK and OFDM with MATLAB System Objects . . . . . . . .
2-64
2-58
2-62
Accelerating BER Simulations Using the Parallel Computing
Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-68
3
4
Visualization and Measurements
Scatter Plot and Eye Diagram with MATLAB Functions . . .
3-2
EVM and MER Measurements with Simulink . . . . . . . . . . . .
3-9
ACPR and CCDF Measurements with MATLAB System
Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ACPR Measurements . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CCDF Measurements . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-16
3-16
3-19
System Objects
What Are System Objects? . . . . . . . . . . . . . . . . . . . . . . . . . . . .
iv
Contents
4-2
System Objects in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . .
System Objects in the MATLAB Function Block . . . . . . . . . .
4-3
4-3
System Object Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are System Object Methods? . . . . . . . . . . . . . . . . . . . .
The Step Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Common Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-4
4-4
4-4
4-5
v
vi
1
Introduction
• “Communications System Toolbox Product Description” on page 1-2
• “System Setup” on page 1-3
• “Access the Block Libraries” on page 1-5
• “Communications System Toolbox Supported Hardware” on page 1-6
1
Introduction
Communications System Toolbox Product Description
Design and simulate the physical layer of communication systems
Communications System Toolbox™ provides algorithms for designing, simulating,
and analyzing communications systems. These capabilities are provided as MATLAB®
functions, MATLAB System objects, and Simulink® blocks. The system toolbox
enables source coding, channel coding, interleaving, modulation, equalization,
synchronization, and channel modeling. You can also analyze bit error rates, generate
eye and constellation diagrams, and visualize channel characteristics. Using adaptive
algorithms, you can model dynamic communications systems that use OFDM, OFDMA,
and MIMO techniques. Algorithms support fixed-point data arithmetic and C or HDL
code generation.
Key Features
• Algorithms for designing the physical layer of communications systems, including
source coding, channel coding, interleaving, modulation, channel models, MIMO,
equalization, and synchronization
• GPU-enabled System objects for computationally intensive algorithms such as Turbo,
LDPC, and Viterbi decoders
• Eye Diagram Scope app and visualization functions for constellations and channel
scattering
• Bit Error Rate app for comparing the simulated bit error rate of a system with
analytical results
• Channel models, including AWGN, Multipath Rayleigh Fading, Rician Fading, MIMO
Multipath Fading, and LTE MIMO Multipath Fading
• Basic RF impairments, including nonlinearity, phase noise, thermal noise, and phase
and frequency offsets
• Algorithms available as MATLAB functions, MATLAB System objects, and Simulink
blocks
• Support for fixed-point modeling and C and HDL code generation
1-2
System Setup
System Setup
In this section...
“Required Products” on page 1-3
“Expected Background” on page 1-3
“Configure the Simulink Environment for Communications Models” on page 1-3
Required Products
The Communications System Toolbox product is part of a family of MathWorks®
products. You need to install several products to use this product. For more
information about the required products, see the MathWorks website, at http://
www.mathworks.com/products/communications/requirements.html.
Expected Background
This documentation assumes that you already have background knowledge in the subject
of digital communications. If you do not yet have this background, then you can acquire
it using a standard communications text or the books listed in the Selected Bibliography
subsections that accompany many topics.
The discussion and examples in this section are aimed at new users. Continue reading
and try the examples. Then, read the subsequent content that pertains to your specific
areas of interest. As you learn which System object™, block, or function you want to use,
refer to the online reference pages for more information.
Configure the Simulink Environment for Communications Models
Using commstartup.m
The Communications System Toolbox product provides a file, commstartup.m. This
file changes the default Simulink model settings to values more appropriate for the
simulation of communication systems. The changes apply to new models that you create
later in the MATLAB session, but not to previously created models.
Note The DSP System Toolbox™ application includes a similar dspstartup script, which
assigns different model settings. For modeling communication systems, you should use
commstartup alone.
1-3
1
Introduction
To install the communications-related model settings each time you start MATLAB,
invoke commstartup from your startup.m file. The settings in commstartup cause
models to:
• Use the variable-step discrete solver in single-tasking mode
• Use starting and ending times of 0 and Inf, respectively
• Avoid producing a warning or error message for inherited sample times in source
blocks
• Set the Simulink Boolean logic signals parameter to Off
• Avoid saving output or time information to the workspace
• Produce an error upon detecting an algebraic loop
• Inline parameters if you use the Model Reference feature of Simulink
If your communications model does not work well with these default settings, you can
change each of the individual settings as the model requires.
1-4
Access the Block Libraries
Access the Block Libraries
To view the block libraries for the products you have installed, type simulink at
the MATLAB prompt (or click the Simulink button on the MATLAB toolbar). The
Simulink Library Browser appears.
Simulink Library Browser
The left pane displays the installed products, each of which has its own library of blocks.
To open a library, click the + sign next to the product name in the left pane. This displays
the contents of the library in the right pane.
You can find the blocks you need to build communications system models in the
Communications System Toolbox, DSP System Toolbox, and Simulink libraries.
Alternatively, you can access the main Communications System Toolbox block library by
entering commlib at the MATLAB command line.
1-5
1
Introduction
Communications System Toolbox Supported Hardware
As of this release, Communications System Toolbox supports the following hardware.
Support Package
Vendor
Platforms
Earliest Release
Available
Last Release
Available
“RTL-SDR Radio”
NooElec
Windows®
R2013b
Current
“USRP® Radio”
National
Instruments
Windows, Mac,
Linux®
R2011b
Current
“Xilinx FPGA-Based
Radio”
Xilinx
Windows, Mac,
Linux
R2013b
Current
For a complete list of supported hardware, see Hardware Support.
1-6
2
System Simulation
• “256-QAM with Simulink Blocks” on page 2-2
• “16-QAM with MATLAB Functions” on page 2-11
• “Iterative Design Workflow for Communication Systems” on page 2-33
• “QPSK and OFDM with MATLAB System Objects” on page 2-64
• “Accelerating BER Simulations Using the Parallel Computing Toolbox” on page
2-68
2
System Simulation
256-QAM with Simulink Blocks
In this section...
“Section Overview” on page 2-2
“Opening the Model” on page 2-2
“Overview of the Model” on page 2-3
“Quadrature Amplitude Modulation” on page 2-4
“Run a Simulation” on page 2-5
“Display the Error Rate” on page 2-6
“Set Block Parameters” on page 2-7
“Display a Phase Noise Plot” on page 2-9
Section Overview
This section describes an example model of a communications system. The model
displays a scatter plot of a signal with added noise. The purpose of this section is to
familiarize you with the basics of Simulink models and how they function.
Opening the Model
To open the model, first start MATLAB. In the MATLAB Command Window, enter
doc_commphasenoise at the prompt. This opens the model in a new window, as shown in
the following figure.
2-2
256-QAM with Simulink Blocks
Overview of the Model
The model shown in the preceding section, “Opening the Model” on page 2-2,
simulates the effect of phase noise on quadrature amplitude modulation (QAM) of a
signal. The Simulink model is a graphical representation of a mathematical model of a
communication system that generates a random signal, modulates it using QAM, and
adds noise to simulate a channel. The model also contains components for displaying the
symbol error rate and a scatter plot of the modulated signal.
The blocks and lines in the Simulink model describe mathematical relationships among
signals and states:
• The Random Integer Generator block, labeled Random Integer, generates a signal
consisting of a sequence of random integers between zero and 255
• The Rectangular QAM Modulator Baseband block, to the right of the Random Integer
Generator block, modulates the signal using baseband 256-ary QAM.
• The AWGN Channel block models a noisy channel by adding white Gaussian noise to
the modulated signal.
• The Phase Noise block introduces noise in the angle of its complex input signal.
• The Rectangular QAM Demodulator Baseband block, to the right of the Phase Noise
block, demodulates the signal.
2-3
2
System Simulation
In addition, the following blocks in the model help you interpret the simulation:
• The Constellation Diagram block, labeled AWGN plus Phase Noise, displays a scatter
plot of the signal with added noise.
• The Error Rate Calculation block counts symbols that differ between the received
signal and the transmitted signal.
• The Display block, at the far right of the model window, displays the symbol error
rate (SER), the total number of errors, and the total number of symbols processed
during the simulation.
All these blocks are included in Communications System Toolbox. You can find more
detailed information about these blocks by right-clicking the block and selecting Help
from the context menu.
Quadrature Amplitude Modulation
This model simulates quadrature amplitude modulation (QAM), which is a method for
converting a digital signal to a complex signal. The model modulates the signal onto a
sequence of complex numbers that lie on a lattice of points in the complex plane, called
the constellation of the signal. The constellation for baseband 256-ary QAM is shown in
the following figure.
2-4
256-QAM with Simulink Blocks
Constellation for 256-ary QAM
Run a Simulation
To run a simulation, click on the Run button at the top of the model window.
The simulation stops automatically at the Stop time, which is specified in the
Configuration Parameters dialog box. You can stop the simulation at any time
by selecting Stop from the Simulation menu at the top of the model window (or, on
Microsoft Windows, by clicking the Stop button on the toolstrip).
When you run the model, a new window appears, displaying a scatter plot of the
modulated signal with added noise, as shown in the following figure.
2-5
2
System Simulation
Scatter Plot of Signal Plus Noise
The points in the scatter plot do not lie exactly on the constellation shown in the figure
because of the added noise. The radial pattern of points is due to the addition of phase
noise, which alters the angle of the complex modulated signal.
Display the Error Rate
The Display block displays the number of errors introduced by the channel noise. When
you run the simulation, three small boxes appear in the block, as shown in the following
figure, displaying the vector output from the Error Rate Calculation block.
Note: The image below is a representative example and may not exactly match results
you see when running in Simulink.
2-6
256-QAM with Simulink Blocks
Error Rate Display
The block displays the output as follows:
• The first entry is the symbol error rate (SER).
• The second entry is the total number of errors.
• The third entry is the total number of comparisons made. The notation 1e+004 is
shorthand for 104.
Set Block Parameters
You can control the way a Simulink block functions by setting its parameters. To view or
change a block's parameters, double-click the block. This opens a dialog box, sometimes
called the block's mask. For example, the dialog box for the Phase Noise block is shown in
the following figure.
2-7
2
System Simulation
Dialog for the Phase Noise Block
2-8
256-QAM with Simulink Blocks
To change the amount of phase noise, click in the Phase noise level (dBc/Hz) field and
enter a new value. Then click OK.
Alternatively, you can enter a variable name, such as phasenoise, in the field. You
can then set a value for that variable in the MATLAB Command Window, for example
by entering phasenoise = -60. Setting parameters in the Command Window is
convenient if you need to run multiple simulations with different parameter values.
You can also change the amount of noise in the AWGN Channel block. Double-click the
block to open its dialog box, and change the value in the Es/No parameter field. This
changes the signal to noise ratio, in dB. Decreasing the value of Es/No increases the
noise level.
You can experiment with the model by changing these or other parameters and then
running a simulation. For example,
• Change Phase noise level (dBc/Hz) to -150 in the dialog box for the Phase Noise
block.
• Change Es/No to 100 in the dialog for the AWGN Channel block.
This removes nearly all noise from the model. When you now run a simulation, the
scatter plot appears as in the figure “Constellation for 256-ary QAM”.
Display a Phase Noise Plot
Double-click the block labeled “Display Figure” at the bottom left of the model window.
This displays a plot showing the results of multiple simulations.
2-9
2
System Simulation
BER Plot at Different Noise Levels
Each curve is a plot of bit error rate as a function of signal to noise ratio for a fixed
amount of phase noise.
You can create plots like this by running multiple simulations with different values for
the Phase noise level (dBc/Hz) and Es/No parameters.
2-10
16-QAM with MATLAB Functions
16-QAM with MATLAB Functions
In this section...
“Introduction” on page 2-11
“Modulate a Random Signal” on page 2-11
“Plot Signal Constellations” on page 2-18
“Pulse Shaping Using a Raised Cosine Filter” on page 2-22
“Error Correction using a Convolutional Code” on page 2-29
Introduction
This section builds an example step-by-step to give you a first look at the
Communications System Toolbox software. This section also shows how Communications
System Toolbox functionalities build upon the computational and visualization tools in
the underlying MATLAB environment.
Modulate a Random Signal
This example shows how to process a binary data stream using a communication system
that consists of a baseband modulator, channel, and demodulator. The system's bit error
rate (BER) is computed and the transmitted and received signals are displayed in a
constellation diagram.
The following table summarizes the basic operations used, along with relevant
Communications System Toolbox and MATLAB functions. The example uses baseband
16-QAM (quadrature amplitude modulation) as the modulation scheme and AWGN
(additive white Gaussian noise) as the channel model.
Task
Function
Generate a Random Binary Data Stream
randi
Convert the Binary Signal to an Integer-Valued
Signal
bi2de
Modulate using 16-QAM
qammod
Add White Gaussian Noise
awgn
2-11
2
System Simulation
Task
Function
Create a Constellation Diagram
scatterplot
Demodulate using 16-QAM
qamdemod
Convert the Integer-Valued Signal to a Binary Signal de2bi
Compute the System BER
biterr
Generate a Random Binary Data Stream
The conventional format for representing a signal in MATLAB is a vector or matrix. This
example uses the randi function to create a column vector that contains the values of a
binary data stream. The length of the binary data stream (that is, the number of rows in
the column vector) is arbitrarily set to 30,000.
The code below also creates a stem plot of a portion of the data stream, showing the
binary values. Notice the use of the colon (:) operator in MATLAB to select a portion of
the vector.
Define parameters.
M = 16;
k = log2(M);
n = 30000;
numSamplesPerSymbol = 1;
%
%
%
%
Size of signal constellation
Number of bits per symbol
Number of bits to process
Oversampling factor
Create a binary data stream as a column vector.
rng default
dataIn = randi([0 1],n,1);
% Use default random number generator
% Generate vector of binary data
Plot the first 40 bits in a stem plot.
stem(dataIn(1:40),'filled');
title('Random Bits');
xlabel('Bit Index');
ylabel('Binary Value');
2-12
16-QAM with MATLAB Functions
Convert the Binary Signal to an Integer-Valued Signal
The qammod function implements a rectangular, M-ary QAM modulator, M being 16 in
this example. The default configuration is such that the object receives integers between
0 and 15 rather than 4-tuples of bits. In this example, we preprocess the binary data
stream dataIn before using the qammod function. In particular, the bi2de function is
used to convert each 4-tuple to a corresponding integer.
Perform a bit-to-symbol mapping.
dataInMatrix = reshape(dataIn,length(dataIn)/4,4);
dataSymbolsIn = bi2de(dataInMatrix);
% Reshape data into binary 4-tuple
% Convert to integers
Plot the first 10 symbols in a stem plot.
2-13
2
System Simulation
figure; % Create new figure window.
stem(dataSymbolsIn(1:10));
title('Random Symbols');
xlabel('Symbol Index');
ylabel('Integer Value');
Modulate using 16-QAM
Having generated the dataSymbolsIn column vector, use the qammod function to apply
16-QAM modulation for both binary and Gray coded bit-to-symbol mappings. Recall that
M is 16, the alphabet size.
Apply modulation.
dataMod = qammod(dataSymbolsIn,M,0);
2-14
% Binary coding, phase offset = 0
16-QAM with MATLAB Functions
dataModG = qammod(dataSymbolsIn,M,0,'gray'); % Gray coding, phase offset = 0
The results are complex column vectors whose values are elements of the 16-QAM signal
constellation. A later step in this example will plot the constellation diagram.
To learn more about modulation functions, see “Digital Modulation”. Also, note that
the qammod function does not apply pulse shaping. To extend this example to use pulse
shaping, see “Pulse Shaping Using a Raised Cosine Filter” on page 2-22. For an
example that uses Gray coding with PSK modulation, see “Gray Coded 8-PSK”.
Add White Gaussian Noise
The ratio of bit energy to noise power spectral density, Eb/N0, is arbitrarily set to 10 dB.
From that value, the signal-to-noise ratio (SNR) can be determined. Given the SNR, the
modulated signal, dataMod, is passed through the channel by using the awgn function.
Note: The numSamplesPerSymbol variable is not significant in this example but will
make it easier to extend the example later to use pulse shaping.
Calculate the SNR when the channel has an Eb/N0 = 10 dB.
EbNo = 10;
snr = EbNo + 10*log10(k) - 10*log10(numSamplesPerSymbol);
Pass the signal through the AWGN channel for both the binary and Gray coded symbol
mappings.
receivedSignal = awgn(dataMod,snr,'measured');
receivedSignalG = awgn(dataModG,snr,'measured');
Create a Constellation Diagram
The scatterplot function is used to display the in-phase and quadrature components
of the modulated signal, dataMod, and its received, noisy version, receivedSignal. By
looking at the resultant diagram, the effects of AWGN are readily observable.
Use the scatterplot function to show the constellation diagram.
sPlotFig = scatterplot(receivedSignal,1,0,'g.');
hold on
scatterplot(dataMod,1,0,'k*',sPlotFig)
2-15
2
System Simulation
Demodulate 16-QAM
The qamdemod function is used to demodulate the received data and output integervalued data symbols.
2-16
16-QAM with MATLAB Functions
Demodulate the received signals using the qamdemod function.
dataSymbolsOut = qamdemod(receivedSignal,M);
dataSymbolsOutG = qamdemod(receivedSignalG,M,0,'gray');
Convert the Integer-Valued Signal to a Binary Signal
The de2bi function is used to convert the data symbols from the QAM demodulator,
dataSymbolsOut, into a binary matrix, dataOutMatrix with dimensions of Nsym-byNbits/sym, where Nsym is the total number of QAM symbols and Nbits/sym is the number of
bits per symbol, four in this case. The matrix is then converted into a column vector
whose length is equal to the number of input bits, 30,000. The process is repeated for the
Gray coded data symbols, dataSymbolsOutG.
Reverse the bit-to-symbol mapping performed earlier.
dataOutMatrix = de2bi(dataSymbolsOut,k);
dataOut = dataOutMatrix(:);
dataOutMatrixG = de2bi(dataSymbolsOutG,k);
dataOutG = dataOutMatrixG(:);
% Return data in column vector
% Return data in column vector
Compute the System BER
The function biterr is used to calculate the bit error statistics from the original binary
data stream, dataIn, and the received data streams, dataOut and dataOutG.
Use the error rate function to compute the error statistics and use fprintf to display
the results.
[numErrors,ber] = biterr(dataIn,dataOut);
fprintf('\nThe binary coding bit error rate = %5.2e, based on %d errors\n', ...
ber,numErrors)
[numErrorsG,berG] = biterr(dataIn,dataOutG);
fprintf('\nThe Gray coding bit error rate = %5.2e, based on %d errors\n', ...
berG,numErrorsG)
The binary coding bit error rate = 2.40e-03, based on 72 errors
The Gray coding bit error rate = 1.33e-03, based on 40 errors
Observe that Gray coding significantly reduces the bit error rate.
2-17
2
System Simulation
Plot Signal Constellations
The example in the previous section, “Modulate a Random Signal” on page 2-11,
created a scatter plot from the modulated signal. Although the plot showed the points
in the QAM constellation, the plot did not indicate which integers of the modulator are
mapped to a given constellation point. This section illustrates two possible mappings:
1) binary coding, and 2) Gray coding. It was previously demonstrated that Gray coding
provides superior bit error rate performance.
Binary Symbol Mapping for 16-QAM Constellation
Apply 16-QAM modulation to all possible input values using the default symbol mapping,
binary.
M = 16;
x = (0:15)';
y1 = qammod(x, 16, 0);
% Modulation order
% Integer input
% 16-QAM output, phase offset = 0
Use the scatterplot function to plot the constellation diagram and annotate it with
binary representations of the constellation points.
scatterplot(y1)
text(real(y1)+0.1, imag(y1), dec2bin(x))
title('16-QAM, Binary Symbol Mapping')
axis([-4 4 -4 4])
2-18
16-QAM with MATLAB Functions
Gray-coded Symbol Mapping for 16-QAM Constellation
Apply 16-QAM modulation to all possible input values using Gray-coded symbol
mapping.
2-19
2
System Simulation
y2 = qammod(x, 16, 0, 'gray');
% 16-QAM output, phase offset = 0, Gray-coded
Use the scatterplot function to plot the constellation diagram and annotate it with
binary representations of the constellation points.
scatterplot(y2)
text(real(y2)+0.1, imag(y2), dec2bin(x))
title('16-QAM, Gray-coded Symbol Mapping')
axis([-4 4 -4 4])
2-20
16-QAM with MATLAB Functions
Examine the Plots
In the binary mapping plot, notice that symbols 1 (0 0 0 1) and 2 (0 0 1 0)
correspond to adjacent constellation points on the left side of the diagram. The binary
2-21
2
System Simulation
representations of these integers differ by two bits unlike the Gray-coded signal
constellation in which each point differs by only one bit from its direct neighbors, which
leads to better BER performance.
Pulse Shaping Using a Raised Cosine Filter
The “Modulate a Random Signal” on page 2-11 example was modified to employ a
pair of square-root raised cosine (RRC) filters to perform pulse shaping and matched
filtering. The filters are created by the rcosdesign function. In “Error Correction using
a Convolutional Code” on page 2-29, this example is extended by introducing forward
error correction (FEC) to improve BER performance.
To create a BER simulation, a modulator, demodulator, communication channel, and
error counter functions must be used and certain key parameters must be specified. In
this case, 16-QAM modulation is used in an AWGN channel.
Establish Simulation Framework
Set the simulation parameters.
M = 16;
k = log2(M);
numBits = 3e5;
numSamplesPerSymbol = 4;
%
%
%
%
Size of signal constellation
Number of bits per symbol
Number of bits to process
Oversampling factor
Create Raised Cosine Filter
Set the square-root, raised cosine filter parameters.
span = 10;
rolloff = 0.25;
% Filter span in symbols
% Roloff factor of filter
Create a square-root, raised cosine filter using the rcosdesign function.
rrcFilter = rcosdesign(rolloff, span, numSamplesPerSymbol);
Display the RRC filter impulse response using the fvtool function.
fvtool(rrcFilter,'Analysis','Impulse')
2-22
16-QAM with MATLAB Functions
BER Simulation
Use the randi function to generate random binary data. The rng function should be set
to its default state so that the example produces repeatable results.
rng default
dataIn = randi([0 1], numBits, 1);
% Use default random number generator
% Generate vector of binary data
Reshape the input vector into a matrix of 4-bit binary data, which is then converted into
integer symbols.
dataInMatrix = reshape(dataIn, length(dataIn)/k, k); % Reshape data into binary 4-tuple
dataSymbolsIn = bi2de(dataInMatrix);
% Convert to integers
Apply 16-QAM modulation using qammod.
dataMod = qammod(dataSymbolsIn, M);
Using the upfirdn function, upsample and apply the square-root, raised cosine filter.
2-23
2
System Simulation
txSignal = upfirdn(dataMod, rrcFilter, numSamplesPerSymbol, 1);
The upfirdn function upsamples the modulated signal, dataMod, by a factor of
numSamplesPerSymbol, pads the upsampled signal with zeros at the end to flush the
filter and then applies the filter.
Set the Eb/N0 to 10 dB and convert the SNR given the number of bits per symbol, k, and
the number of samples per symbol.
EbNo = 10;
snr = EbNo + 10*log10(k) - 10*log10(numSamplesPerSymbol);
Pass the filtered signal through an AWGN channel.
rxSignal = awgn(txSignal, snr, 'measured');
Filter the received signal using the square-root, raised cosine filter and remove a
portion of the signal to account for the filter delay in order to make a meaningful BER
comparison.
rxFiltSignal = upfirdn(rxSignal,rrcFilter,1,numSamplesPerSymbol);
rxFiltSignal = rxFiltSignal(span+1:end-span);
% Downsample and fi
% Account for delay
These functions apply the same square-root raised cosine filter that the transmitter used
earlier, and then downsample the result by a factor of nSamplesPerSymbol. The last
command removes the first Span symbols and the last Span symbols in the decimated
signal because they represent the cumulative delay of the two filtering operations. Now
rxFiltSignal, which is the input to the demodulator, and dataSymbolsOut, which is
the output from the modulator, have the same vector size. In the part of the example that
computes the bit error rate, it is required to compare vectors that have the same size.
Apply 16-QAM demodulation to the received, filtered signal.
dataSymbolsOut = qamdemod(rxFiltSignal, M);
Using the de2bi function, convert the incoming integer symbols into binary data.
dataOutMatrix = de2bi(dataSymbolsOut,k);
dataOut = dataOutMatrix(:);
% Return data in column vector
Apply the biterr function to determine the number of errors and the associated BER.
[numErrors, ber] = biterr(dataIn, dataOut);
2-24
16-QAM with MATLAB Functions
fprintf('\nThe bit error rate = %5.2e, based on %d errors\n', ...
ber, numErrors)
The bit error rate = 2.42e-03, based on 727 errors
Visualization of Filter Effects
Create an eye diagram for a portion of the filtered signal.
eyediagram(txSignal(1:2000),numSamplesPerSymbol*2);
2-25
2
System Simulation
2-26
16-QAM with MATLAB Functions
The eyediagram function creates an eye diagram for part of the filtered noiseless signal.
This diagram illustrates the effect of the pulse shaping. Note that the signal shows
significant intersymbol interference (ISI) because the filter is a square-root raised cosine
filter, not a full raised cosine filter.
Created a scatter plot of the received signal before and after filtering.
h = scatterplot(sqrt(numSamplesPerSymbol)*...
rxSignal(1:numSamplesPerSymbol*5e3),...
numSamplesPerSymbol,0,'g.');
hold on;
scatterplot(rxFiltSignal(1:5e3),1,0,'kx',h);
title('Received Signal, Before and After Filtering');
legend('Before Filtering','After Filtering');
axis([-5 5 -5 5]); % Set axis ranges
hold off;
2-27
2
System Simulation
Notice that the first scatterplot command scales rxSignal by
sqrt(numSamplesPerSymbol) when plotting. This is because the filtering operation
changes the signal's power.
2-28
16-QAM with MATLAB Functions
Error Correction using a Convolutional Code
Building upon the “Pulse Shaping Using a Raised Cosine Filter” on page 2-22
example, this example shows how bit error rate performance improves with the addition
of forward error correction, FEC, coding.
Establish Simulation Framework
To create the simulation, a modulator, demodulator, raised cosine filter pair,
communication channel, and error counter functions are used and certain key
parameters are specified. In this case, a 16-QAM modulation scheme with raised cosine
filtering is used in an AWGN channel. With the exception of the number of bits, the
specified parameters are identical to those used in the previous example.
Set the simulation variables. The number of bits is increased from the previous example
so that the bit error rate may be estimated more accurately.
M = 16;
k = log2(M);
numBits = 100000;
numSamplesPerSymbol = 4;
%
%
%
%
Size of signal constellation
Number of bits per symbol
Number of bits to process
Oversampling factor
Generate Random Data
Use the randi function to generate random, binary data once the rng function has been
called. When set to its default value, the rng function ensures that the results from this
example are repeatable.
rng default
dataIn = randi([0 1], numBits, 1);
% Use default random number generator
% Generate vector of binary data
Convolutional Encoding
The performance of the “Pulse Shaping Using a Raised Cosine Filter” on page 2-22
example can be significantly improved upon by employing forward error correction. In
this example, convolutional coding is applied to the transmitted bit stream in order to
correct errors arising from the noisy channel. Because it is often implemented in real
systems, the Viterbi algorithm is used to decode the received data. A hard decision
algorithm is used, which means that the decoder interprets each input as either a “0” or a
“1”.
Define a convolutional coding trellis for a rate 2/3 code. The poly2trellis function
defines the trellis that represents the convolutional code that convenc uses for encoding
2-29
2
System Simulation
the binary vector, dataIn. The two input arguments of the poly2trellis function
indicate the code’s constraint length and generator polynomials, respectively.
tPoly = poly2trellis([5 4],[23 35 0; 0 5 13]);
codeRate = 2/3;
Encode the input data using the previously created trellis.
dataEnc = convenc(dataIn, tPoly);
Modulate Data
The encoded binary data is converted into an integer format so that 16-QAM modulation
can be applied.
Reshape the input vector into a matrix of 4-bit binary data, which is then converted into
integer symbols.
dataEncMatrix = reshape(dataEnc, ...
length(dataEnc)/k, k);
dataSymbolsIn = bi2de(dataEncMatrix);
% Reshape data into binary 4-tuples
% Convert to integers
Apply 16-QAM modulation.
dataMod = qammod(dataSymbolsIn, M);
Raised Cosine Filtering
As in the “Pulse Shaping Using a Raised Cosine Filter” on page 2-22 example, RRC
filtering is applied to the modulated signal before transmission. The example makes use
of the rcosdesign function to create the filter and the upfirdn function to filter the
data.
Specify the filter span and rolloff factor for the square-root, raised cosine filter.
span = 10;
rolloff = 0.25;
% Filter span in symbols
% Roloff factor of filter
Create the filter using the rcosdesign function.
rrcFilter = rcosdesign(rolloff, span, numSamplesPerSymbol);
Using the upfirdn function, upsample and apply the square-root, raised cosine filter.
txSignal = upfirdn(dataMod, rrcFilter, numSamplesPerSymbol, 1);
2-30
16-QAM with MATLAB Functions
AWGN Channel
Calculate the signal-to-noise ratio, SNR, based on the input Eb/N0, the number of
samples per symbol, and the code rate. Converting from Eb/N0 to SNR requires one to
account for the number of information bits per symbol. In the previous example, each
symbol corresponded to k bits. Now, each symbol corresponds to k*codeRate information
bits. More concretely, three symbols correspond to 12 coded bits in 16-QAM, which
correspond to 8 uncoded (information) bits.
EbNo = 10;
snr = EbNo + 10*log10(k*codeRate)-10*log10(numSamplesPerSymbol);
Pass the filtered signal through an AWGN channel.
rxSignal = awgn(txSignal, snr, 'measured');
Receive and Demodulate Signal
Filter the received signal using the RRC filter and remove a portion of the signal to
account for the filter delay in order to make a meaningful BER comparison.
rxFiltSignal = upfirdn(rxSignal,rrcFilter,1,numSamplesPerSymbol);
rxFiltSignal = rxFiltSignal(span+1:end-span);
% Downsample and fi
% Account for delay
Demodulate the received, filtered signal using the qamdemod function.
dataSymbolsOut = qamdemod(rxFiltSignal, M);
Viterbi Decoding
Use the de2bi function to convert the incoming integer symbols into bits.
dataOutMatrix = de2bi(dataSymbolsOut,k);
codedDataOut = dataOutMatrix(:);
% Return data in column vector
Decode the convolutionally encoded data with a Viterbi decoder. The syntax for the
vitdec function instructs it to use hard decisions. The 'cont' argument instructs it to
use a mode designed for maintaining continuity when the function is repeatedly invoked
(as in a loop). Although this example does not use a loop, the 'cont' mode is used for the
purpose of illustrating how to compensate for the delay in this decoding operation.
traceBack = 16;
numCodeWords = floor(length(codedDataOut)*2/3);
dataOut = vitdec(codedDataOut(1:numCodeWords*3/2), ...
% Traceback length for deco
% Number of complete codewo
% Decode data
2-31
2
System Simulation
tPoly,traceBack,'cont','hard');
BER Calculation
Using the biterr function, compare dataIn and dataOut to obtain the number of
errors and the bit error rate while taking the decoding delay into account. The continuous
operation mode of the Viterbi decoder incurs a delay whose duration in bits equals the
traceback length, traceBack, times the number of input streams at the encoder. For
this rate 2/3 code, the encoder has two input streams, so the delay is 2×traceBack
bits. As a result, the first 2×traceBack bits in the decoded vector, dataOut, are zeros.
When computing the bit error rate, the first 2×traceBack bits in dataOut and the
last 2×traceBack bits in the original vector, dataIn, are discarded. Without delay
compensation, the BER computation is meaningless.
decDelay = 2*traceBack;
[numErrors, ber] = ...
biterr(dataIn(1:end-decDelay),dataOut(decDelay+1:end));
% Decoder delay, in bits
fprintf('\nThe bit error rate = %5.2e, based on %d errors\n', ...
ber, numErrors)
The bit error rate = 6.90e-04, based on 69 errors
It can be seen that for the same Eb/N0 of 10 dB, the number of errors when using FEC is
reduced as the BER is improves from 2.0×10-3 to 6.9×10-4.
More About Delays
The decoding operation in this example incurs a delay, which means that the output of
the decoder lags the input. Timing information does not appear explicitly in the example,
and the duration of the delay depends on the specific operations being performed. Delays
occur in various communications-related operations, including convolutional decoding,
convolutional interleaving/deinterleaving, equalization, and filtering. To find out the
duration of the delay caused by specific functions or operations, refer to the specific
documentation for those functions or operations. For example:
• The “vitdec” reference page
• “Delays of Convolutional Interleavers”
• “Fading Channels”
2-32
Iterative Design Workflow for Communication Systems
Iterative Design Workflow for Communication Systems
In this section...
“Simulate a basic communications system” on page 2-34
“Introduce convolutional coding and hard-decision Viterbi decoding” on page 2-38
“Improve results using soft-decision decoding” on page 2-42
“Use turbo coding to improve BER performance” on page 2-47
“Apply a Rayleigh channel model” on page 2-50
“Use OFDM-based equalization to correct multipath fading” on page 2-55
“Use multiple antennas to further improve system performance” on page 2-58
“Accelerate the simulation using MATLAB Coder” on page 2-62
This example illustrates a design workflow that represents the iterative steps for
creating a wireless communications system with the Communications System Toolbox.
Because Communications System Toolbox supports both MATLAB and Simulink,
this example showcases design paths using MATLAB code and Simulink blocks. As
you progress through the workflow, you may follow the design path for MATLAB, for
Simulink, or for both products.
The workflow begins with a simple communications system and performs bit error
rate (BER) simulations to gauge system performance. BER simulations are based on
simulating a communications system with a given signal-to-noise ratio (En/No), and then
calculating the corresponding bit error rate measurement to determine the number of
errors in the transmitted signal. The lower the BER measurement at a given signal-tonoise ratio, the better the system performance.
This workflow starts with a simple communications system, and iteratively adds the
algorithmic components necessary to build a more complicated system. These additional
components include:
• Convolutional Encoding and Viterbi Decoding
• Turbo Coding
• Multipath Fading Channels
• OFDM-Based Transmission
• Multiple-Antenna Techniques
2-33
2
System Simulation
As you add components to the system, the workflow includes bit error calculations so that
you can progressively examine system performance. For some components, theoretical
or performance benchmarks are available. In these cases, the workflow shows both the
theoretical and measured performance metric.
Simulate a basic communications system
This workflow starts with a simple QPSK modulator system that transmits a signal
through an AWGN channel and calculates the bit error rate to evaluate system
performance.
In MATLAB
1
CD to the following MATLAB folder:
2
matlab\help\toolbox\comm\examples
Type edit doc_design_iteration_basic_m at the MATLAB command line.
4
MATLAB opens a file you will use in this example. Notice that this code employs
four System objects from Communications System Toolbox: comm.PSKModulator,
comm.AWGN, comm.PSKDemodulator, and comm.ErrorRate. For each EbNo value,
the code runs in a while loop until either the specified number of errors are observed
or the maximum number of bits are processed. Notice that the code executes each
System object by calling the step method. The code outputs BER, defined as the
ratio of the observed number of errors per number of bits processed. The subsequent
MATLAB functions that this example uses have a similar structure.
Type bertool at the MATLAB command line to open the Bit Error Rate Analysis
Tool.
When the BERTool application appears, click the Theoretical tab.
5
The first plot that you will generate is a theoretical curve.
Enter 0:9 for the EbNo range.
6
EbNo is the ratio of noise power energy per bit. The higher the value, the better the
system performance. This simulation will run using different values for the ratio,
between 0 and 9.
Select 4 for Modulation order.
3
The modulation order defines the number of symbols to transmit. Here, each symbol
is made up of two bits.
2-34
In MATLAB
7
Click Plot.
8
The BERTool application generates the theoretical BER curve.
Cick the Monte Carlo tab.
Monte Carlo techniques use random sampling to compute data. Therefore, the plot
for the second simulation uses random sampling.
9 Enter 0:9 for the EbNo range.
10 Enter ber for the BER variable name.
11 Enter 200 for the Number of errors.
The Number of errors is one of the stop criteria for the simulation.
12 Enter 1e7 for the Number of bits.
The Number of bits is also a stop criteria for the simulation. The simulation stops
when it transmits the number of bits you specify for this parameter. In this example,
the simulation either stops when it transmits 10 million bits or when it detects 200
errors.
13 Click the Browse button.
14 Navigate to matlab/help/toolbox/comm/examples, and select
doc_design_iteration_basic_m.m.
15 Click Run.
BERTool runs the simulation and generates simulation points along the BER curve.
Compare the simulation BER curve with the theoretical BER curve.
2-35
2
System Simulation
Every function with two output variables and three input variables can be called
using BERTool. This is how you interpret the three input variables:
• The first variable is a scalar number that corresponds to EbNo.
• The second variable is the stopping criterion based on the maximum number of
errors to observe before stopping the simulation.
2-36
In Simulink
• The third variable is the stop criterion based on the maximum number of bits to
process before observe before stopping the simulation.
In Simulink
2
3
Type bertool at the MATLAB command line to open the Bit Error Rate Analysis
Tool.
When the BERTool application appears, click the Theoretical tab.
Enter 0:9 for the EbNo range.
4
EbNo is the ratio of noise power energy per bit. The higher the value, the better the
system performance. This simulation will run using different values for the ratio,
between 0 and 9.
Select 4 for Modulation order.
5
The modulation order defines the number of symbols to transmit. Here, each symbol
is made up of two bits.
Click Plot.
6
7
8
9
The BERTool application generates the theoretical BER curve.
Click the Monte Carlo tab.
Enter 0:9 or the EbNo range.
Enter ber for the BER variable name.
Enter 200 for the Number of errors.
1
The Number of errors is one of the stop criteria for the simulation. The simulation
stops when it reaches either the Number of errors or the Number of bits.
10 Enter 1e7 for the Number of bits.
The Number of bits is also a stop criteria for the simulation. The simulation stops
when it transmits the number of bits you specify for this parameter or when it
reaches the Number of errors. In this example, the simulation either stops when it
transmits 10 million bits or when it detects 200 errors.
11 Click the Browse button, select All Files for the Files of type field.
12 Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_basic.slx and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
Compare the simulation BER curve with the theoretical BER curve.
2-37
2
System Simulation
Introduce convolutional coding and hard-decision Viterbi decoding
Modify the basic communications model to include forward error correction. Adding
forward error correction to the basic communications model improves system
performance. In forward error correction, the transmitter sends redundant bits, along
2-38
In MATLAB
with the message bits, through a wireless channel. When the receiver accepts the
transmitted signal, it uses the redundancy bits to detect and correct errors that the
channel may have introduced.
This section of the design workflow adds a convolutional encoder and a Viterbi decoder
to the communication system. This communications system uses hard-decision Viterbi
decoding. In hard-decision Viterbi decoding, the demodulator maps the received signal to
bits, and then passes the bits to the Viterbi decoder for error correction.
In MATLAB
In this iteration of the design workflow, the MATLAB file you use starts from where the
one in the previous section ended. This file adds two additional System objects to the
communications system, comm.ConvolutionalEncoder and comm.ViterbiDecoder.
The overall structure of the code doesn't change; it simply contains additional
functionality.
1
2
3
4
5
6
Access the BERTool application.
Clear the Plot check boxes for the two plots BERTool generated in the previous step.
Click Theoretical.
Enter 0:7 for the EbNo range.
Select Convolutional for the Channel Coding.
Select Hard for the Decision method.
7
This example uses hard-decision Viterbi decoding. The demodulator maps the
received signal to bits, and then passes the bits to the Viterbi decoder for error
correction.
Click Plot.
The BERTool application generates the theoretical BER curve.
Click Monte Carlo.
Enter 0:7 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_m.m and click Open.
14 Click Run.
8
9
10
11
12
13
2-39
2
System Simulation
BERTool runs the simulation and generates simulated points along the BER curve.
Compare the simulation BER curve with the theoretical BER curve.
2-40
In Simulink
In Simulink
1
2
3
4
5
Access the BERTool application.
Click the Theoretical tab.
Enter 0:7 for the EbNo range.
Select Convolutional for the Channel Coding.
Select Hard for the Decision method.
6
This example uses hard-decision Viterbi decoding. The demodulator maps the
received signal to bits, and then passes the bits to the Viterbi decoder for error
correction.
Click Plot.
The BERTool application generates the theoretical BER curve.
Click the Monte Carlo tab.
Enter 0:7 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button, select All Files for the Files of type field.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi.slx and click Open.
13 click Run.BERTool runs the simulation and generates simulated points along the
BER curve. Compare the simulation BER curve with the theoretical BER curve.
7
8
9
10
11
12
2-41
2
System Simulation
Improve results using soft-decision decoding
Use soft-decision decoding to improve BER performance. The previous section of
this workflow uses hard-decision demodulation and hard-decision Viterbi decoding
– processes that map symbols to bits. This section of the workflow uses soft-decision
2-42
In MATLAB
demodulation and soft-decision Viterbi decoding. In soft-decision demodulation, the
received symbols are not mapped to bits. Instead, the symbols are mapped to loglikelihood ratios. When the Viterbi decoder processes log-likelihood ratios (LLR), the BER
performance of the system improves.
In MATLAB
1
2
3
4
5
Access the BERTool application.
Clear the Plot check boxes for the two plots BERTool generated in the previous step.
Click Theoretical.
Enter 0:5 for the EbNo range.
Select Soft for the Decision method.
6
This example uses soft-decision Viterbi decoding. The demodulator maps the
received signal to log likelihood ratios, improving BER performance results.
Click Plot.
7
8
9
10
11
12
The BERTool application generates the theoretical BER curve.
Click Monte Carlo.
Enter 0:5 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_soft_m.m and click Run.
BERTool runs the simulation and generates the actual simulated points along the
BER curve. Compare the simulation BER curve with the theoretical BER curve.
2-43
2
System Simulation
In Simulink
1
2-44
Access the BERTool application.
In Simulink
2
3
4
5
Clear the Plot check boxes for the two plots BERTool generated in the previous step.
Click Theoretical.
Enter 0:5for the EbNo range.
Select Soft for the Decision method.
6
This example uses soft-decision Viterbi decoding. The demodulator maps the
received signal to log likelihood ratios, improving BER performance results.
Click Plot.
7
8
9
10
11
12
The BERTool application generates the theoretical BER curve.
Click Monte Carlo.
Enter 0:5 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button, select All Files for the Files of type field.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_soft.slx and click Run.
2-45
2
System Simulation
When you plot the soft-decision theoretical curve, you will observe BER curve
improvements of about 2 dB relative to the hard-decision decoding. Notice that the
simulation results also reflects a similar BER improvement.
2-46
In MATLAB
Use turbo coding to improve BER performance
Turbo codes substantially improve BER performance over soft-decision Viterbi decoding.
Turbo coding uses two convolutional encoders in parallel at the transmitter and two a
posteriori probability (APP) decoders in series at the receiver. This example uses a rate
1/3 turbo coder. For each input bit, the output has 1 systematic bit and 2 parity bits, for
a total of three bits. Turbo coders achieve BER performances at much lower SNR values
than convolutional encoders. As a result, this iteration uses a lower range of EbNo values
than the previous section.
In MATLAB
1
2
3
4
5
6
7
Access the BERTool application.
Click the Monte Carlo tab.
Enter 0:0.2:1.2 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_zTurbo_soft_m.m and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
2-47
2
System Simulation
In Simulink
1
2
2-48
Access the BERTool application.
Clear the Plot check boxes for the last plot BERTool generated in the previous
section.
In Simulink
3
4
5
6
7
8
Click the Monte Carlo tab.
Enter 0:0.2:1.2 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button, select All Files for the Files of type field.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_turbo.slx and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
2-49
2
System Simulation
Apply a Rayleigh channel model
The previous design iterations model narrowband communications systems that
can be adequately represented using an AWGN channel. However, high data rate
communications systems require a wideband channel. Wideband communications
2-50
In MATLAB
channels are highly susceptible to the effects of multipath propagation, which introduces
intersymbol interference (ISI). Therefore, you must model wideband channels as
multipath fading channels. This iteration of the design workflow uses a multipath fading
Rayleigh channel, which assumes no direct line-of-sight between the transmitter and
receiver.
In MATLAB
1
2
3
4
5
6
7
8
Access the BERTool application.
Clear the Plot check box for the plot BERTool generated in the previous step.
Click Monte Carlo.
Enter 0:9 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_rayleigh_m.m and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
Compare the simulation BER curve with the theoretical BER curve.
2-51
2
System Simulation
In the presence of multipath fading, the BER performance reduces to that of a binary
channel with a consistent value of one-half. To correct the effect of multipath fading,
you must add equalization to the communications system.
2-52
In Simulink
In Simulink
1
2
3
4
5
6
7
8
Access the BERTool application.
Clear the Plot check box to clear the plot BERTool generated in the previous step.
Click Monte Carlo.
Enter 0:7 for the EbNo range.
Enter 200 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button, select All Files for the Files of type field.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_rayleigh.slx and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
Compare the simulation BER curve with the theoretical BER curve.
2-53
2
System Simulation
In the presence of multipath fading, the BER performance reduces to that of a binary
channel with a consistent value of one-half. To correct the effect of multipath fading,
you must add equalization to the communications system.
2-54
In MATLAB
Use OFDM-based equalization to correct multipath fading
Use orthogonal frequency-division multiplexing (OFDM) to compensate for the multipath
fading effect introduced by the Rayleigh fading channel. OFDM transmission schemes
provides an effective way to perform frequency domain equalization. This design
iteration introduces an OFDM transmitter, an OFDM receiver, and a frequency domain
equalizer to the communications system.
In MATLAB
1
2
3
4
5
6
7
8
Access the BERTool application.
Clear the Plot check boxes for the simulation plot generated in the previous step.
Click the Monte Carlo tab.
Enter 0:9 for the EbNo range.
Enter 6000 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_Rayleigh_OFDM_m.m and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
2-55
2
System Simulation
In Simulink
1
2
3
2-56
Access the BERTool application.
Clear the Plot check boxes for the plots BERTool generated in the previous step.
Click the Monte Carlo tab.
In Simulink
4
5
6
7
8
Enter 0:9 for the EbNo range.
Enter 6000 for the Number of errors.
Enter 5e7 for the Number of bits.
Click the Browse button, select All Files for the Files of type field.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_rayleigh_OFDM.slx and click Run.
BERTool runs the simulation and generates simulated points. Compare the
simulation BER curve with the theoretical BER curve.
2-57
2
System Simulation
Use multiple antennas to further improve system performance
Simultaneously transmitting copies of a signal using multiple antennas can significantly
increase the likelihood that the receiver correctly recovers the transmitted signal. This
2-58
In MATLAB
phenomenon is known as transmit diversity. However, this performance improvement
comes at the expense of introducing additional computational complexity in the receiver.
In MATLAB
1
2
3
4
5
6
7
8
Access the BERTool application.
Clear the Plot check box to clear the simulation plot generated in the previous step.
Click the Monte Carlo tab.
Enter 0:9 for the EbNo range.
Enter 1000 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_rayleigh_OFDM_MIMO_m.m and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
Compare the simulation BER curve with the theoretical BER curve.
2-59
2
System Simulation
In Simulink
1
2
3
2-60
Access the BERTool application.
Click the Monte Carlo tab.
Enter 0:9 for the EbNo range.
In Simulink
4
5
6
7
Enter 700 for the Number of errors.
Enter 1e7 for the Number of bits.
Click the Browse button, select All Files for the Files of type field.
Navigate to matlab/help/toolbox/comm/examples, select
doc_design_iteration_viterbi_rayleigh_OFDM_MIMO.slx and click Run.
2-61
2
System Simulation
Accelerate the simulation using MATLAB Coder
All of the functions and System objects that this design iteration workflow uses support
C code generation. If you have a MATLAB Coder™ license, you can accelerate simulation
speed by generating a .mex file using the codegen command.
In MATLAB
1
2
3
Copy the doc_design_iteration_viterbi_rayleigh_OFDM_MIMO_m.m file to a folder
that is not on the MATLAB path. For example, C:\Temp.
Change your working directory to the folder you just created.
Execute the following commands to set a numerical value for each of the input
arguments in the doc_design_iteration_viterbi_rayleigh_OFDM_MIMO_m function.
For example:
EbNo=1;
MaxNumErrs=200;
MaxNumBits=1e7;
4
5
Execute the codegen command to generate the executable MATLAB file.
codegen -args {EbNo,MaxNumErrs,MaxNumBits}
doc_design_iteration_viterbi_rayleigh_OFDM_MIMO_m
The file extension of the MATLAB executable file that gets generated
depends upon your operating system. For example, on 64–bit Windows
the file extension will be .mexw64, and the full file name will be
doc_design_iteration_viterbi_rayleigh_OFDM_MIMO_m_mex.mexw64.
If you run the mex file you just generated in BERTool, you will obtain the simulation
results more quickly.
6 Access the BERTool application.
7 Click the Monte Carlo tab.
8 Enter 0:9 for the EbNo range.
9 Enter 700 for the Number of errors.
10 Enter 1e7 for the Number of bits.
11 Click the Browse button, and select All Files.
Navigate to folder you created in step 1 and click Run.
BERTool runs the simulation and generates simulated points along the BER curve.
Compare the simulation BER curve with the previous curve. Any variation in the
2-62
In MATLAB
BER curve of the mex file and the MATLAB file from which it was generated is
related to the seed of the random number generator and is statistically insignificant.
In this example, BERTool generates the curve much more quickly when you use
MATLAB Coder to generate C code. Notice that BERTool generates similar BER
results in about 1/4 of the time that it took for the original simulation took to
complete.
2-63
2
System Simulation
QPSK and OFDM with MATLAB System Objects
This example shows how to simulate a basic communication system in which the
signal is first QPSK modulated and then subjected to Orthogonal Frequency Division
Multiplexing. The signal is then passed through an additive white Gaussian noise
channel prior to being demultiplexed and demodulated. Lastly, the number of bit errors
are calculated. The example showcases the use of MATLAB® System objects™.
Set the simulation parameters.
M = 4;
k = log2(M);
numSC = 128;
cpLen = 32;
maxBitErrors = 100;
maxNumBits = 1e7;
%
%
%
%
%
%
Modulation alphabet
Bits/symbol
Number of OFDM subcarriers
OFDM cyclic prefix length
Maximum number of bit errors
Maximum number of bits transmitted
Construct System objects needed for the simulation: QPSK modulator, QPSK
demodulator, OFDM modulator, OFDM demodulator, AWGN channel, and an error rate
calculator. Use name-value pairs to set the object properties.
Set the QPSK modulator and demodulator so that they accept binary inputs.
hQPSKMod = comm.QPSKModulator('BitInput',true);
hQPSKDemod = comm.QPSKDemodulator('BitOutput',true);
Set the the OFDM modulator and demodulator pair according to the simulation
parameters.
hOFDMmod = comm.OFDMModulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hOFDMdemod = comm.OFDMDemodulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
Set the NoiseMethod property of the AWGN channel object to Variance and define the
VarianceSource property so that the noise power can be set from an input port.
hChan = comm.AWGNChannel('NoiseMethod','Variance', ...
'VarianceSource','Input port');
Set the ResetInputPort property to true to enable the error rate calculator to be reset
during the simulation.
hError = comm.ErrorRate('ResetInputPort',true);
2-64
QPSK and OFDM with MATLAB System Objects
Use the info function of the hOFDMmod object to determine the input and output
dimensions of the OFDM modulator.
ofdmInfo = info(hOFDMmod)
ofdmInfo =
DataInputSize: [117 1]
OutputSize: [160 1]
Determine the number of data subcarriers from the ofdmInfo structure variable.
numDC = ofdmInfo.DataInputSize(1)
numDC =
117
Determine the OFDM frame size (in bits) from the number of data subcarriers and the
number of bits per symbol.
frameSize = [k*numDC 1];
Set the SNR vector based on the desired Eb/No range, the number of bits per symbol, and
the ratio of the number of data subcarriers to the total number of subcarriers.
EbNoVec = (0:10)';
snrVec = EbNoVec + 10*log10(k) + 10*log10(numDC/numSC);
Initialize the BER and error statistics arrays.
berVec = zeros(length(EbNoVec),3);
errorStats = zeros(1,3);
Simulate the communication link over the range of Eb/No values. For each Eb/No value,
the simulation runs until either maxBitErrors are recorded or the total number of
transmitted bits exceeds maxNumBits.
for m = 1:length(EbNoVec)
2-65
2
System Simulation
snr = snrVec(m);
while errorStats(2) <= maxBitErrors && errorStats(3) <= maxNumBits
dataIn = randi([0,1],frameSize);
% Generate binary data
qpskTx = step(hQPSKMod,dataIn);
% Apply QPSK modulation
txSig = step(hOFDMmod,qpskTx);
% Apply OFDM modulation
powerDB = 10*log10(var(txSig));
% Calculate Tx signal power
noiseVar = 10.^(0.1*(powerDB-snr));
% Calculate the noise variance
rxSig = step(hChan,txSig,noiseVar);
% Pass the signal through a noisy
qpskRx = step(hOFDMdemod,rxSig);
% Apply OFDM demodulation
dataOut = step(hQPSKDemod,qpskRx);
% Apply QPSK demodulation
errorStats = step(hError,dataIn,dataOut,0);
% Collect error statistics
end
berVec(m,:) = errorStats;
errorStats = step(hError,dataIn,dataOut,1);
% Save BER data
% Reset the error rate calculator
end
Use the berawgn function to determine the theoretical BER for a QPSK system.
berTheory = berawgn(EbNoVec,'psk',M,'nondiff');
Plot the theoretical and simulated data on the same graph to compare results.
figure
semilogy(EbNoVec,berVec(:,1),'*')
hold on
semilogy(EbNoVec,berTheory)
legend('Simulation','Theory','Location','Best')
xlabel('Eb/No (dB)')
ylabel('Bit Error Rate')
grid on
hold off
2-66
QPSK and OFDM with MATLAB System Objects
Observe that there is good agreement between the simulated and theoretical data.
2-67
2
System Simulation
Accelerating BER Simulations Using the Parallel Computing
Toolbox
This example shows how to use the Parallel Computing Toolbox™ to accelerate a simple,
QPSK bit error rate (BER) simulation. The system consists of a QPSK modulator, a
QPSK demodulator, an AWGN channel, and a bit error rate counter. In this example,
four parallel processors are used.
Set the simulation parameters.
EbNoVec = 5:8;
totalErrors = 200;
totalBits = 1e7;
% Eb/No values in dB
% Number of bit errors needed for each Eb/No value
% Total number of bits transmitted for each Eb/No value
Allocate memory to the arrays used to store the data generated by the function,
doc_fcn_qpsk_sim_with_awgn.
[numErrors, numBits] = deal(zeros(length(EbNoVec),1));
Run the simulation and determine the execution time. Only one processor will be used
to determine baseline performance. Accordingly, observe that the normal for-loop is
employed.
tic
for idx = 1:length(EbNoVec)
errorStats = doc_fcn_qpsk_sim_with_awgn(EbNoVec, idx, ...
totalErrors, totalBits);
numErrors(idx) = errorStats(idx,2);
numBits(idx) = errorStats(idx,3);
end
simBaselineTime = toc;
Calculate the BER.
ber1 = numErrors ./ numBits;
Rerun the simulation for the case in which the Parallel Computing Toolbox is available.
Create a pool of workers.
pool = gcp;
Starting parallel pool (parpool) using the 'local' profile ... connected to 4 workers.
2-68
Accelerating BER Simulations Using the Parallel Computing Toolbox
Determine the number of available workers from the NumWorkers property of pool.
The simulation runs the range of Eb/N0 values over each worker rather than assigning
a single Eb/N0 point to each worker as the former method provides the biggest
performance improvement.
numWorkers = pool.NumWorkers;
Determine the length of EbNoVec for use in the nested parfor loop. For proper variable
classification, the range of a for-loop nested in a parfor must be defined by constant
numbers or variables.
lenEbNoVec = length(EbNoVec);
Allocate memory to the arrays used to store the data generated by the function,
doc_fcn_qpsk_sim_with_awgn.
[numErrors, numBits] = deal(zeros(length(EbNoVec),numWorkers));
Run the simulation and determine the execution time.
tic
parfor n = 1:numWorkers
for idx = 1:lenEbNoVec
errorStats = doc_fcn_qpsk_sim_with_awgn(EbNoVec, idx, ...
totalErrors/numWorkers, totalBits/numWorkers);
numErrors(idx,n) = errorStats(idx,2);
numBits(idx,n) = errorStats(idx,3);
end
end
simParallelTime = toc;
Calculate the BER. In this case, the results from multiple processors must be combined
to generate the aggregate BER.
ber2 = sum(numErrors,2) ./ sum(numBits,2);
Compare the BER values to verify that the same results are obtained independent of the
number of workers.
semilogy(EbNoVec',ber1,'-*',EbNoVec',ber2,'-^')
legend('Single Processor','Multiple Processors','location','best')
2-69
2
System Simulation
xlabel('Eb/No (dB)')
ylabel('BER')
grid
You can see that the BER curves are essentially the same with any variance being due to
differing random number seeds.
Compare the execution times for each method.
fprintf(['\nSimulation time = %4.1f sec for one worker\n', ...
'Simulation time = %4.1f sec for multiple workers\n'], ...
simBaselineTime, simParallelTime)
Simulation time = 170.1 sec for one worker
2-70
Accelerating BER Simulations Using the Parallel Computing Toolbox
Simulation time = 52.7 sec for multiple workers
In this case where four processor cores were used, the speed improvement factor was
approximately four.
2-71
2-72
3
Visualization and Measurements
• “Scatter Plot and Eye Diagram with MATLAB Functions” on page 3-2
• “EVM and MER Measurements with Simulink” on page 3-9
• “ACPR and CCDF Measurements with MATLAB System Objects” on page 3-16
3
Visualization and Measurements
Scatter Plot and Eye Diagram with MATLAB Functions
This example shows how to use the Communications System Toolbox to visualize signal
behavior through the use of eye diagrams and scatter plots. The example uses a QPSK
signal which is passed through a square-root raised cosine (RRC) filter.
Scatter Plot
Set the RRC filter, modulation scheme, and plotting parameters.
span = 10;
rolloff = 0.2;
sps = 8;
M = 4;
k = log2(M);
phOffset = pi/4;
n = 1;
offset = 0;
%
%
%
%
%
%
%
%
Filter span
Rolloff factor
Samples per symbol
Modulation alphabet size
Bits/symbol
Phase offset (radians)
Plot every nth value of the signal
Plot every nth value of the signal, starting from offset+1
Create the filter coefficients using the rcosdesign function.
filtCoeff = rcosdesign(rolloff,span,sps);
Generate random symbols for an alphabet size of M.
rng default
data = randi([0 M-1],5000,1);
Apply QPSK modulation.
dataMod = pskmod(data,M,phOffset);
Filter the modulated data.
txSig = upfirdn(dataMod,filtCoeff,sps);
Calculate the SNR for an oversampled QPSK signal.
EbNo = 20;
snr = EbNo + 10*log10(k) - 10*log10(sps);
Add AWGN to the transmitted signal.
3-2
Scatter Plot and Eye Diagram with MATLAB Functions
rxSig = awgn(txSig,snr,'measured');
Apply the RRC receive filter.
rxSigFilt = upfirdn(rxSig, filtCoeff,1,sps);
Demodulate the filtered signal.
dataOut = pskdemod(rxSigFilt,M,phOffset,'gray');
Use the scatterplot function to show scatter plots of the signal before and after
filtering. You can see that the receive filter improves performance as the constellation
more closely matches the ideal values. The first span symbols and the last span symbols
represent the cummulative delay of the two filtering operations and are removed from
the two filtered signals before generating the scatter plots.
h = scatterplot(sqrt(sps)*txSig(sps*span+1:end-sps*span),sps,offset,'g.');
hold on
scatterplot(rxSigFilt(span+1:end-span),n,offset,'kx',h)
scatterplot(dataMod,n,offset,'r*',h)
legend('Transmit Signal','Received Signal','Ideal','location','best')
3-3
3
Visualization and Measurements
Eye Diagram
Display 1000 points of the transmitted signal eye diagram over two symbol periods.
eyediagram(txSig(sps*span+1:sps*span+1000),2*sps)
3-4
Scatter Plot and Eye Diagram with MATLAB Functions
3-5
3
Visualization and Measurements
Display 1000 points of the received signal eye diagram.
eyediagram(rxSig(sps*span+1:sps*span+1000),2*sps)
3-6
Scatter Plot and Eye Diagram with MATLAB Functions
3-7
3
Visualization and Measurements
Observe that the received eye diagram begins to close due to the presence of AWGN.
Moreover, the filter has finite length which also contributes to the non-ideal behavior.
3-8
EVM and MER Measurements with Simulink
EVM and MER Measurements with Simulink
This model shows how error vector magnitude (EVM) and modulation error rate (MER)
measurements are made using Simulink blocks.
Load the model doc_mer_and_evm from the MATLAB command prompt.
doc_mer_and_evm
This example includes:
• A 16-QAM modulated signal
• An I/Q imbalance
• A constellation diagram block
• EVM Measurement and MER Measurement blocks
The model applies an I/Q imbalance to a QAM-modulated signal at which point MER
and EVM measurements are made. The constellation diagram provides a visual
representation of the effects the imbalance has on the modulation performance
indicators.
3-9
3
Visualization and Measurements
The I/Q Imbalance block is set to that the I/Q amplitude imbalance (dB) is set to 1
and the I/Q phase imbalance (deg) is set to 15.
The MER Measurement block is set so that it outputs the X-percentile MER value which
is set to 90%.
3-10
EVM and MER Measurements with Simulink
The EVM Measurement block is set to output the maximum and 75th percentile EVM
values.
3-11
3
Visualization and Measurements
Run the model.
3-12
EVM and MER Measurements with Simulink
You can see that I/Q amplitude and phase imbalance has shifted the constellation
diagram so that each symbol is not exactly equal to its reference symbol (shown in
red). Change the I/Q Imbalance block to see the effects of differing imbalances on the
constellation diagram.
Observe the EVM and MER values. For the default configuration of the model, the mean
MER is approximately 16.9 dB and the 90th percentile MER is 13.9 dB. The RMS EVM
is, approximately, 14.3%, the maximum EVM is 20.4%, and the 75th percentile EVM is
17.7%.
3-13
3
Visualization and Measurements
Change the I/Q amplitude imbalance (dB) value in the I/Q Imbalance block to 2 dB.
You can see that the all the MER and EVM metrics degrade.
3-14
EVM and MER Measurements with Simulink
3-15
3
Visualization and Measurements
ACPR and CCDF Measurements with MATLAB System Objects
In this section...
“ACPR Measurements” on page 3-16
“CCDF Measurements” on page 3-19
ACPR Measurements
This example shows how to measure the adjacent channel power ratio (ACPR) from
a baseband, 50 kbps QPSK signal. ACPR is the ratio of signal power measured in an
adjacent frequency band to the power from the same signal measured in its main band.
The number of samples per symbol is set to four.
Set the random number generator so that results are repeatable.
prevState = rng;
rng(577)
Set the samples per symbol (sps) and channel bandwidth (bw) parameters.
sps = 4;
bw = 50e3;
Generate 10,000 4-ary symbols for QSPK modulation.
data = randi([0, 3],10000,1);
Construct a QPSK modulator and then modulate the input data.
hMod = comm.QPSKModulator;
x = step(hMod, data);
Apply rectangular pulse shaping to the modulated signal. This type of pulse shaping is
typically not done in practical system but is used here for illustrative purposes.
y = rectpulse(x, sps);
Construct an ACPR System object. The sample rate is the bandwidth multiplied by
the number of samples per symbol. The main channel is assumed to be at 0 while the
adjacent channel offset is set to 50 kHz (identical to the bandwidth of the main channel).
3-16
ACPR and CCDF Measurements with MATLAB System Objects
Likewise, the measurement bandwidth of the adjacent channel is set to be the same as
the main channel. Lately, enable the main and adjacent channel power output ports.
hACPR = comm.ACPR('SampleRate',bw*sps,...
'MainChannelFrequency',0,...
'MainMeasurementBandwidth',bw,...
'AdjacentChannelOffset',50e3,...
'AdjacentMeasurementBandwidth',bw,...
'MainChannelPowerOutputPort', true,...
'AdjacentChannelPowerOutputPort',true);
Use the step method of the comm.ACPR System object to output the ACPR, the main
channel power, and the adjacent channel power for the signal, y.
[ACPR, mainPower, adjPower] = step(hACPR, y)
ACPR =
-9.5103
mainPower =
28.9634
adjPower =
19.4531
Change the frequency offset to 75 kHz and determine the ACPR. Since the
AdjacentChannelOffset property is nontunable, you must first release hACPR. Observe
that the ACPR improves when the channel offset is increased.
release(hACPR)
hACPR.AdjacentChannelOffset = 75e3;
ACPR = step(hACPR, y)
ACPR =
-13.2317
3-17
3
Visualization and Measurements
Reset hACPR and specify a 50 kHz adjacent channel offset.
release(hACPR)
hACPR.AdjacentChannelOffset = 50e3;
Create a raised cosine filter and filter the modulated signal.
hFilt = comm.RaisedCosineTransmitFilter('OutputSamplesPerSymbol', sps);
z = step(hFilt, x);
Measure the ACPR for the filtered signal, z . You can see that the ACPR improves from
-9.5 dB to -17.7 dB when raised cosine pulses are used.
ACPR = step(hACPR, z)
ACPR =
-17.7338
Plot the adjacent channel power ratios for a range of adjacent channel offsets. Set the
channel offsets to range from 30 kHz to 70 kHz in 10 kHz steps. Recall that you must
first release hACPR to change the offset.
freqOffset = 1e3*(30:5:70);
release(hACPR)
hACPR.AdjacentChannelOffset = freqOffset;
Determine the ACPR values for the signals with rectangular and raised cosine pulse
shapes.
ACPR1 = step(hACPR, y);
ACPR2 = step(hACPR, z);
Plot the adjacent channel power ratios.
plot(freqOffset/1000,ACPR1,'*-',freqOffset/1000, ACPR2,'o-')
xlabel('Adjacent Channel Offset (kHz)')
ylabel('ACPR (dB)')
legend('Rectangular','Raised Cosine','location','best')
grid
3-18
ACPR and CCDF Measurements with MATLAB System Objects
Return the random number generator to its initial state.
rng(prevState)
CCDF Measurements
This example shows how to use the Complementary Cumulative Distribution Function
(CCDF) System object to measure the probability of a signal's instantaneous power being
greater than a specified level over its average power. Construct the comm.CCDF object,
enable the PAPR output port, and set the maximum signal power limit to 50 dBm.
hCCDF = comm.CCDF('PAPROutputPort',true, ...
'MaximumPowerLimit', 50);
3-19
3
Visualization and Measurements
Create a 64-QAM modulator and an OFDM modulator. The QAM modulated signal will
be evaluated by itself and evaluated again after OFDM modulation is applied.
hMod = comm.RectangularQAMModulator('ModulationOrder',64);
hOFDM = comm.OFDMModulator('FFTLength', 256, 'CyclicPrefixLength', 32);
Determine the input and output sizes of the OFDM modulator object using the info
method of the comm.OFDMModulator object.
info(hOFDM)
ofdmInputSize = hOFDM.info.DataInputSize;
ofdmOutputSize = hOFDM.info.OutputSize;
ans =
DataInputSize: [245 1]
OutputSize: [288 1]
Set the number of OFDM frames.
numFrames = 20;
Allocate memory for the signal arrays.
qamSig = repmat(zeros(ofdmInputSize), numFrames, 1);
ofdmSig = repmat(zeros(ofdmOutputSize), numFrames, 1);
Use the default random number generator to ensure repeatability.
rng default
Generate the 64-QAM and OFDM signals for evaluation.
for k = 1:numFrames
% Generate random data symbols
data = randi([0, 63], ofdmInputSize);
% Apply 64-QAM modulation
tmpQAM = step(hMod, data);
% Apply OFDM modulation to the QAM-modulated signal
tmpOFDM = step(hOFDM, tmpQAM);
% Save the signal data
qamSig((1:ofdmInputSize)+(k-1)*ofdmInputSize(1)) = tmpQAM;
ofdmSig((1:ofdmOutputSize)+(k-1)*ofdmOutputSize(1)) = tmpOFDM;
3-20
ACPR and CCDF Measurements with MATLAB System Objects
end
Determine the average signal power, the peak signal power, and the PAPR ratios for the
two signals. The two signals being evaluated must be the same length so the first 4000
symbols are evaluated.
[Fy, Fx, PAPR] = step(hCCDF, [qamSig(1:4000), ...
ofdmSig(1:4000)]);
Plot the CCDF data. Observe that the likelihood of the power of the OFDM modulated
signal being more than 3 dB above its average power level is much higher than for the
QAM modulated signal.
plot(hCCDF)
legend('QAM','OFDM','location','best')
3-21
3
Visualization and Measurements
Compare the PAPR values for the QAM modulated and OFDM modulated signals.
fprintf('\nPAPR for 64-QAM = %5.2f dB\nPAPR for OFDM = %5.2f dB\n',...
PAPR(1), PAPR(2))
PAPR for 64-QAM = 3.65 dB
PAPR for OFDM = 9.44 dB
You can see that by applying OFDM modulation to a 64-QAM modulated signal, the
PAPR increases by 5.8 dB. This means that if 30 dBm transmit power is needed to close
a 64-QAM link, the power amplifier needs to have a maximum power of 33.7 dBm to
ensure linear operation. If the same signal were then OFDM modulated, a 39.5 dBm
power amplifier is required.
3-22
4
System Objects
• “What Are System Objects?” on page 4-2
• “System Objects in Simulink” on page 4-3
• “System Object Methods” on page 4-4
4
System Objects
What Are System Objects?
A System object is a specialized kind of MATLAB object. System Toolboxes include
System objects and most System Toolboxes also have MATLAB functions and Simulink
blocks. System objects are designed specifically for implementing and simulating
dynamic systems with inputs that change over time. Many signal processing,
communications, and controls systems are dynamic. In a dynamic system, the values
of the output signals depend on both the instantaneous values of the input signals and
on the past behavior of the system. System objects use internal states to store that past
behavior, which is used in the next computational step. As a result, System objects are
optimized for iterative computations that process large streams of data, such as video
and audio processing systems.
For example, you could use System objects in a system that reads data from a file,
filters that data and then writes the filtered output to another file. Typically, a specified
amount of data is passed to the filter in each loop iteration. The file reader object uses
a state to keep track of where in the file to begin the next data read. Likewise, the file
writer object keeps tracks of where it last wrote data to the output file so that data is not
overwritten. The filter object maintains its own internal states to assure that the filtering
is performed correctly. This diagram represents a single loop of the system.
Many System objects support:
• Fixed-point arithmetic (requires a Fixed-Point Designer™ license)
• C code generation (requires a MATLAB Coder or Simulink Coder license)
• HDL code generation (requires an HDL Coder™ license)
• Executable files or shared libraries generation (requires a MATLAB Compiler™
license)
Note: Check your product documentation to confirm fixed-point, code generation, and
MATLAB Compiler support for the specific System objects you want to use.
4-2
System Objects in Simulink
System Objects in Simulink
System Objects in the MATLAB Function Block
You can include System object code in Simulink models using the MATLAB Function
block. Your function can include one or more System objects. Portions of your system may
be easier to implement in the MATLAB environment than directly in Simulink. Many
System objects have Simulink block counterparts with equivalent functionality. Before
writing MATLAB code to include in a Simulink model, check for existing blocks that
perform the desired operation.
4-3
4
System Objects
System Object Methods
In this section...
“What Are System Object Methods?” on page 4-4
“The Step Method” on page 4-4
“Common Methods” on page 4-5
What Are System Object Methods?
After you create a System object, you use various object methods to process data or
obtain information from or about the object. All methods that are applicable to an object
are described in the reference pages for that object. System object method names begin
with a lowercase letter and class and property names begin with an uppercase letter.
The syntax for using methods is <method>(<handle>), such as step(H), plus possible
extra input arguments.
System objects use a minimum of two commands to process data—a constructor to
create the object and the step method to run data through the object. This separation
of declaration from execution lets you create multiple, persistent, reusable objects,
each with different settings. Using this approach avoids repeated input validation
and verification, allows for easy use within a programming loop, and improves overall
performance. In contrast, MATLAB functions must validate parameters every time you
call the function.
These advantages make System objects particularly well suited for processing streaming
data, where segments of a continuous data stream are processed iteratively. This ability
to process streaming data provides the advantage of not having to hold large amounts of
data in memory. Use of streaming data also allows you to use simplified programs that
use loops efficiently.
The Step Method
The step method is the key System object method. You use step to process data using
the algorithm defined by that object. The step method performs other important tasks
related to data processing, such as initialization and handling object states. Every
System object has its own customized step method, which is described in detail on the
step reference page for that object. For more information about the step method and
other available methods, see the descriptions in “Common Methods” on page 4-5.
4-4
System Object Methods
Common Methods
All System objects support the following methods, each of which is described in a method
reference page associated with the particular object. In cases where a method is not
applicable to a particular object, calling that method has no effect on the object.
Method
Description
step
Processes data using the algorithm defined by the object. As
part of this processing, it initializes needed resources, returns
outputs, and updates the object states. After you call the
step method, you cannot change any input specifications (i.e.,
dimensions, data type, complexity). During execution, you can
change only tunable properties. The step method returns
regular MATLAB variables.
Example: Y = step(H,X)
release
Releases any special resources allocated by the object, such
as file handles and device drivers, and unlocks the object.
For System objects, use the release method instead of a
destructor.
reset
Resets the internal states of the object to the initial values for
that object
getNumInputs
Returns the number of inputs (excluding the object itself)
expected by the step method. This number varies for an object
depending on whether any properties enable additional inputs.
getNumOutputs
Returns the number of outputs expected from the step
method. This number varies for an object depending on
whether any properties enable additional outputs.
getDiscreteState
Returns the discrete states of the object in a structure. If the
object is unlocked (when the object is first created and before
you have run the step method on it or after you have released
the object), the states are empty. If the object has no discrete
states, getDiscreteState returns an empty structure.
clone
Creates another object of the same type with the same property
values
isLocked
Returns a logical value indicating whether the object is locked.
4-5
4
4-6
System Objects
Method
Description
isDone
Applies to source objects only. Returns a logical value
indicating whether the step method has reached the end of
the data file. If a particular object does not have end-of-data
capability, this method value returns false.
info
Returns a structure containing characteristic information
about the object. The fields of this structure vary depending on
the object. If a particular object does not have characteristic
information, the structure is empty.