100% found this document useful (2 votes)
2K views118 pages

Embedded Matlab

Embedded MATLAB(tm) Getting Started Guide is furnished under a license agreement. No part of this manual may be photocopied or reproduced without prior written consent. MATLAB and Simulink are registered trademarks of the MathWorks, Inc.

Uploaded by

joseluisgg
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views118 pages

Embedded Matlab

Embedded MATLAB(tm) Getting Started Guide is furnished under a license agreement. No part of this manual may be photocopied or reproduced without prior written consent. MATLAB and Simulink are registered trademarks of the MathWorks, Inc.

Uploaded by

joseluisgg
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

Embedded MATLAB™

Getting Started Guide


How to Contact The MathWorks

www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.com/contact_TS.html Technical Support

suggest@mathworks.com Product enhancement suggestions


bugs@mathworks.com Bug reports
doc@mathworks.com Documentation error reports
service@mathworks.com Order status, license renewals, passcodes
info@mathworks.com Sales, pricing, and general information

508-647-7000 (Phone)

508-647-7001 (Fax)

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
Embedded MATLAB™ Getting Started Guide
© COPYRIGHT 2008–2009 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
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
October 2008 Online only New for Release 2008b
March 2009 Online only Revised for Release 2009a
September 2009 Online only Revised for Release 2009b
Contents

Introduction to the Embedded MATLAB Subset


1
What Is the Embedded MATLAB Subset? ............ 1-2

When to Use the Embedded MATLAB Subset . . . . . . . . . 1-3

Which Embedded MATLAB Feature to Use . . . . . . . . . . . 1-4

When Not to Use the Embedded MATLAB Subset . . . . . 1-6

Benefits of Using the Embedded MATLAB Subset . . . . . 1-7

Tutorial Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8


What You Need to Know . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Required Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8

Generating C Code from MATLAB Code for


Embedded Applications
2
Tasks For Generating C Code . . . . . . . . . . . . . . . . . . . . . . . 2-2

Design Considerations for Code Generation . . . . . . . . . . 2-3

Example: The LMS Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4


Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
The Filtering Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6

iii
Files for This Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
About the Tutorial Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Location of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Names and Descriptions of Files . . . . . . . . . . . . . . . . . . . . . 2-8

Making Your M-Code Compliant with the


Embedded MATLAB Subset
3
Considerations for Making Your Code Compliant . . . . . 3-2
Designing for Compliance . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Checking for Violations at Design Time . . . . . . . . . . . . . . . 3-2
Checking for Violations at Code Generation Time . . . . . . . 3-2
Where to Go Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3

Making the LMS Filter Code Embedded MATLAB


Compliant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Copying Files Locally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Setting Up Your C Compiler . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Compiling M-Code Using emlmex . . . . . . . . . . . . . . . . . . . . 3-6
Next Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-16
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-16
Best Practices Used in This Section . . . . . . . . . . . . . . . . . . . 3-17

Testing Compliant Code in MATLAB


4
Generating MEX Functions Using Build Scripts . . . . . . 4-2
Why Use Build Scripts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Contents of the Example Build Script . . . . . . . . . . . . . . . . . 4-2
Using the Example Build Script . . . . . . . . . . . . . . . . . . . . . . 4-3

Testing MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5


Why Use Test Scripts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Contents of the Example Test Script . . . . . . . . . . . . . . . . . . 4-5
Using the Test Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8

iv Contents
Next Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11
Best Practices Used in This Section . . . . . . . . . . . . . . . . . . . 4-12

Generating C Code
5
Generating C Code Using emlc . . . . . . . . . . . . . . . . . . . . . . 5-2
Prerequisites for Generating C Code . . . . . . . . . . . . . . . . . . 5-2
Contents of the Example Build Script . . . . . . . . . . . . . . . . . 5-2
Using the Example Build Script . . . . . . . . . . . . . . . . . . . . . . 5-3
Comparing the Generated C Code to Original M-Code . . . . 5-6
Next Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
Best Practices Used in This Section . . . . . . . . . . . . . . . . . . . 5-8

Elaborating Your Algorithm for Embedded


Implementation
6
Modifying the Filter to Accept a Variable Length
Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Why Modify the Filter Algorithm? . . . . . . . . . . . . . . . . . . . . 6-2
Examining the Generated C Code . . . . . . . . . . . . . . . . . . . . 6-2
Modifying Your M-Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Generating C Code For Your Modified M-Code . . . . . . . . . . 6-5
Testing Your MEX Function . . . . . . . . . . . . . . . . . . . . . . . . . 6-6

Modifying the Filter to Use Streaming . . . . . . . . . . . . . . . 6-7


What Is Streaming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Why Use Streaming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Modifying Your M-Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
How to Generate C Code for Your Modified M-Code . . . . . . 6-10
How to Test Your MEX Function . . . . . . . . . . . . . . . . . . . . . 6-10

Adding Adapt and Reset Controls . . . . . . . . . . . . . . . . . . . 6-13


Why Add Adapt and Reset Controls . . . . . . . . . . . . . . . . . . . 6-13
Modifying Your M-Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13

v
How to Generate C Code for Your Modified M-Code . . . . . . 6-15
How to Test Your MEX Function . . . . . . . . . . . . . . . . . . . . . 6-15
Next Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15

Where to Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16


Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16
Product Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-17
The MathWorks Online . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-17

Integrating Your Embedded MATLAB


Compliant Code with Simulink
7
Tasks for Integrating with Simulink . . . . . . . . . . . . . . . . . 7-2

Integrating with Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Files Supplied with This Tutorial . . . . . . . . . . . . . . . . . . . . 7-4
Adding an Embedded MATLAB Function Block to Your
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Calling Your M-Code from the Embedded MATLAB
Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Connecting the Embedded MATLAB Function Block Inputs
and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8
Configuring Embedded MATLAB Outputs . . . . . . . . . . . . . 7-10
Running the emldemo_noise_cancel_01 Model . . . . . . . . . . 7-11
Using eml.extrinsic to Debug Your M-Code . . . . . . . . . . . . 7-14
Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15
Best Practice Used in This Section . . . . . . . . . . . . . . . . . . . 7-15

Best Practices for Working with the Embedded


MATLAB Subset
8
Recommended Compilation Options for emlmex . . . . . . 8-2
-eg Specify Input Parameters by Example . . . . . . . . . . . . . 8-2

vi Contents
-o Specify Output File Name . . . . . . . . . . . . . . . . . . . . . . . . 8-2
-report Generate Compilation Report . . . . . . . . . . . . . . . . . 8-3

Recommended Compilation Options for emlc . . . . . . . . 8-4


-c Generate Code Only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
-report Generate Compilation Report . . . . . . . . . . . . . . . . . 8-4

Using Build Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5

Using M-Lint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7


Using M-Lint to Check Code Interactively at Design
Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7

Separating Your Test Bench from Your Function


Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8

Comparing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9


Comparing Two Versions of a File Using the MATLAB
Compare Against Option . . . . . . . . . . . . . . . . . . . . . . . . . 8-9
Comparing C Code and M-Code Using Tiling in the
MATLAB Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11

Testing MEX Functions in MATLAB . . . . . . . . . . . . . . . . . 8-13

Preserving Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-14

File Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-15

Index

vii
viii Contents
1

Introduction to the
Embedded MATLAB Subset

• “What Is the Embedded MATLAB Subset?” on page 1-2


• “When to Use the Embedded MATLAB Subset” on page 1-3
• “Which Embedded MATLAB Feature to Use” on page 1-4
• “When Not to Use the Embedded MATLAB Subset” on page 1-6
• “Benefits of Using the Embedded MATLAB Subset” on page 1-7
• “Tutorial Prerequisites” on page 1-8
1 Introduction to the Embedded MATLAB™ Subset

What Is the Embedded MATLAB Subset?


Embedded MATLAB™ is a subset of the MATLAB® language. The Embedded
MATLAB subset supports efficient code generation for prototyping and
deploying embedded systems, and accelerating of fixed-point algorithms. It
consists of more than 270 MATLAB operators and functions and more than
90 functions from Fixed-Point Toolbox™ software.

See “Overview of the Embedded MATLAB Subset” in the Embedded MATLAB


User’s Guide for more information.

1-2
When to Use the Embedded MATLAB™ Subset

When to Use the Embedded MATLAB Subset


Use the Embedded MATLAB subset to:

• Generate readable, efficient, and embeddable C code from M-code


• Generate MEX functions from M-code for rapid prototyping and easy
verification of generated C code within MATLAB
• Integrate M-code into Simulink®
• Speed up fixed-point M-code
• Integrate custom C code into MATLAB
• Generate hardware description language (HDL) from M-code

For the function, command, or block that applies, see “Which Embedded
MATLAB Feature to Use” on page 1-4.

1-3
1 Introduction to the Embedded MATLAB™ Subset

Which Embedded MATLAB Feature to Use


To... Use... Required Product To Explore Further...

Generate MEX emlmex function Simulink or Try this in “Compiling


functions for rapid Fixed-Point Toolbox M-Code Using
prototyping emlmex” on page
3-6
emlc command Real-Time Workshop® Try this in
“Generating C Code
Using emlc” on page
5-2
Generate readable emlc command Real-Time Workshop Try this in Chapter 5,
and embeddable C “Generating C Code”
code from M-code
Integrate M-code into Embedded MATLAB Simulink Try this in Chapter
Simulink function block 7, “Integrating Your
Embedded MATLAB
Compliant Code with
Simulink”
Speed up fixed-point emlmex function Fixed-Point Toolbox Learn more in
M-code “Working with
Embedded MATLAB
MEX” in the
Embedded MATLAB
User’s Guide
Integrate custom C emlc function Real-Time Workshop Learn more in
code into MATLAB “Converting MATLAB
and generate Code to C Code” in the
embeddable code Real-Time Workshop
User’s Guide

1-4
Which Embedded MATLAB™ Feature to Use

To... Use... Required Product To Explore Further...

Integrate custom eml.ceval function Real-Time Workshop Learn more in


C code into an eml.ceval in the
Embedded MATLAB Embedded MATLAB
function Reference
Generate HDL from Embedded MATLAB Simulink and Learn more at
M-code function block Simulink® HDL www.mathworks.com/
Coder™ products/slhdlcoder

1-5
1 Introduction to the Embedded MATLAB™ Subset

When Not to Use the Embedded MATLAB Subset


The Embedded MATLAB subset is not designed for the following applications.
Use the recommended MathWorks™ product instead.

To... Use...
Deploy an application that uses “MATLAB Compiler™”
handle graphics
Use Java™ “MATLAB® Builder JA”
Use toolbox functions that the Toolbox functions that you rewrite
Embedded MATLAB subset does for embedded applications
not support
Deploy M-based GUI applications “MATLAB Compiler™”
on a supported MATLAB host
Deploy web-based or Windows® “MATLAB® Builder NE”
applications
Interface C code with MATLAB MATLAB mex function

1-6
Benefits of Using the Embedded MATLAB™ Subset

Benefits of Using the Embedded MATLAB Subset


Working with the Embedded MATLAB subset allows you to perform your
embedded software design, implementation, and testing completely within
the MATLAB workspace. In addition, it enables you to generate efficient,
readable, and embeddable C code automatically from your M-code.

Within the MATLAB development environment, you can:

• Ensure your M-code is compliant with the Embedded MATLAB subset.


• Generate C code automatically from your M-code, which eliminates the
need to manually translate your MATLAB algorithms and minimizes the
risk of introducing errors in the code.
• Modify your design in M-code to take into account the specific requirements
of embedded applications, such as data type management, memory use,
and speed.
• Test the generated code and easily verify that your modified algorithms are
functionally equivalent to your original MATLAB algorithms.

1-7
1 Introduction to the Embedded MATLAB™ Subset

Tutorial Prerequisites
In this section...
“What You Need to Know” on page 1-8
“Required Products” on page 1-8

What You Need to Know


This tutorial involves two key procedures:

• Generating C code from M-code for embedded applications


In this part of the tutorial, you make your M-code Embedded MATLAB
compliant and then generate C code.
To complete this part of the tutorial, you should have basic familiarity with
MATLAB software. You do not need to be familiar with or use Simulink
or Real-Time Workshop software.
• Integrating Embedded MATLAB compliant code with Simulink
In this part of the tutorial, you integrate your M-code with Simulink using
the Embedded MATLAB Function block.
To complete this part of the tutorial, you should understand how to
create a basic Simulink model and how to simulate that model. For
more information, see “Simulink Software Basics” in the Simulink
documentation.

Required Products
To complete this tutorial, you must install the following products:

• MATLAB
• Simulink
• Fixed-Point Toolbox (required when using fixed-point capabilities)
• Real-Time Workshop
• C compiler (a default C compiler is supplied with MATLAB)

1-8
Tutorial Prerequisites

For instructions on installing MathWorks products, see the MATLAB


installation documentation for your platform. If you have installed MATLAB
and want to check which other MathWorks products are installed, enter
ver in the MATLAB Command Window. For instructions on installing and
setting up a C compiler, see “Setting Up the C Compiler” in the Embedded
MATLAB User’s Guide.

1-9
1 Introduction to the Embedded MATLAB™ Subset

1-10
2

Generating C Code
from MATLAB Code for
Embedded Applications

• “Tasks For Generating C Code” on page 2-2


• “Design Considerations for Code Generation” on page 2-3
• “Example: The LMS Filter” on page 2-4
• “Files for This Tutorial” on page 2-7
2 Generating C Code from MATLAB® Code for Embedded Applications

Tasks For Generating C Code


Here is a flow chart showing the tasks for generating C code with the
Embedded MATLAB subset from existing MATLAB code:

To get you started quickly, this tutorial guides you through hands-on exercises
for each task in the flow chart. When you get to task 4, you might need to
iterate between generating C code and elaborating your Embedded MATLAB
compliant code. Elaboration is the process of refining the design of your
M-code as you work toward producing the most efficient, embeddable C code.

To learn more about what to consider when converting M-code into


embeddable C code, see “Design Considerations for Code Generation” on page
2-3.

To view the complete list of the best practices recommended in this tutorial,
see Chapter 8, “Best Practices for Working with the Embedded MATLAB
Subset”.

2-2
Design Considerations for Code Generation

Design Considerations for Code Generation


To convert MATLAB code into efficient, embeddable C code, you must
consider the following:

• Data types
C uses static typing. Therefore, you must declare the data type of all
variables at compile time.
• Array sizing
The Embedded MATLAB subset supports variable-size arrays and matrices
with known upper bounds. With this feature, you can define inputs,
outputs, and local variables in Embedded MATLAB functions to represent
data that varies in size at runtime.
For more information, see “Generating Code for Variable-Size Data” in the
Embedded MATLAB™ User’s Guide.

Note The LMS filter example in this tutorial uses static array sizing.

• Memory use
Because dynamic memory allocation is not suitable for mission or
safety-critical applications, the Embedded MATLAB subset supports only
static memory allocation in the generated code.
• Speed
Because embedded applications need to run in real time, the code must be
fast enough to meet the required clock rate.
• Memory
Embedded processors have a limited amount of available memory. As a
result, data storage must be minimized, and the code must be as compact
as possible.

To learn how to apply these design considerations, you work with “Example:
The LMS Filter” on page 2-4.

2-3
2 Generating C Code from MATLAB® Code for Embedded Applications

Example: The LMS Filter


In this section...
“Description” on page 2-4
“Algorithm” on page 2-4
“The Filtering Process” on page 2-5
“Reference” on page 2-6

Description
A least mean squares (LMS) filter is an adaptive filter that adjusts its transfer
function according to an optimizing algorithm. You provide the filter with
an example of the desired output together with the input signal. The filter
then calculates the filter weights, or coefficients, that produce the least mean
squares of the error between the output signal and the desired signal.

The example for this tutorial uses a LMS filter to remove the noise in a music
recording. This example uses two inputs. The first input is the distorted
signal: the music recording plus noise. The second input is the noise. The
filter works to eliminate the difference between these two signals and outputs
the difference, which, in this case, is the clean music recording. When you
start the simulation, you hear both noise and the music. Over time, the
adaptive filter filters out the noise so you hear only the music.

Algorithm
This tutorial uses the least mean squares (LMS) algorithm to remove noise
from an input signal. The LMS algorithm computes the filtered output, filter
error, and filter weights given the distorted and desired signals.

The LMS algorithm at the start of the tutorial uses a batch process to filter
the audio input. This algorithm is suitable for MATLAB, where you are likely
to load in the entire signal and process it all at once. However, a batch process
is not suitable for processing a signal in real time. As you work through the
tutorial, you refine the design of the filter to convert the algorithm from
batch-based to stream-based processing.

2-4
Example: The LMS Filter

Note The LMS filter example in this tutorial uses static array sizing. The
Embedded MATLAB subset supports variable-size arrays and matrices with
known upper bounds. With this feature, you can define inputs, outputs,
and local variables in Embedded MATLAB functions to represent data that
varies in size at runtime. For more information, see “Generating Code for
Variable-Size Data” in the Embedded MATLAB™ User’s Guide.

The function signature for the algorithm is:

function [ signal_out, err, weights ] = lms(distorted, desired )

The filtering is performed in the following loop:

for n = 1:N
signal_out(n) = weights' * distorted(n:n+L-1);
err(n) = desired(n) - signal_out(n) ;
weights = weights + mu*err(n)*distorted(n:n+L-1);
end

where N is the length of the input signal, L is the filter length, and mu is the
adaptation step size.

What is the adaptation step size?

LMS algorithms have a step size that determines the amount of correction
to apply as the filter adapts from one iteration to the next. Choosing the
appropriate step size requires experience in adaptive filter design. A step
size that is too small increases the time for the filter to converge. Filter
convergence is the process where the error signal (the difference between the
output signal and the desired signal) approaches an equilibrium state over
time. A step size that is too large might cause the adapting filter to overshoot
the equilibrium and become unstable, which is undesirable. Generally,
smaller step sizes improve the stability of the filter at the expense of the
time it takes to adapt.

The Filtering Process


The filtering process has three phases:

2-5
2 Generating C Code from MATLAB® Code for Embedded Applications

• Convolution
The convolution for the filter is performed in:

signal_out(n) = weights' * distorted(n:n+L-1);

What is convolution?

Convolution is the mathematical foundation of filtering. In signal


processing, convolving two vectors or matrices is equivalent to filtering one
of the inputs by the other. In this implementation of the LMS filter, the
convolution operation is the vector dot product between the filter weights
and a subset of the distorted input signal.
• Calculation of error
The error is the difference between the desired signal and the output signal:

err(n) = desired(n) - signal_out(n);

• Adaptation
The new value of the filter weights is the old value of the filter weights plus
a correction factor that is based on the error signal, the distorted signal,
and the adaptation step size:

weights = weights + mu*err(n)*distorted(n:n+L-1);

Reference
Haykin, Simon, Adaptive Filter Theory, Prentice-Hall, Inc., 1996

2-6
Files for This Tutorial

Files for This Tutorial


In this section...
“About the Tutorial Files” on page 2-7
“Location of Files” on page 2-8
“Names and Descriptions of Files” on page 2-8

About the Tutorial Files


The tutorial uses the following files:

• Example M-code files for each step of the tutorial.


Throughout this tutorial, you work with M-files that contain a simple least
mean squares (LMS) filter algorithm.
• Build scripts that you use to compile your function code.
• Test files that:
- Perform the preprocessing functions, for example, setting up the signal
length and filter length
- Load the music sample
- Call the specified filter function
- Compare the outputs of the specified filter function (the algorithm under
test) to the output of the original filter (the golden reference) so that you
can determine if your modified code is functionally equivalent to your
original code
- Perform the post-processing functions, for example, plotting the filter’s
impulse response and playing the audio output
• A MAT-file that contains the filter coefficients.
• Simulink models for Chapter 7, “Integrating Your Embedded MATLAB
Compliant Code with Simulink” .

2-7
2 Generating C Code from MATLAB® Code for Embedded Applications

Location of Files
The tutorial files are located in the folder
matlabroot/toolbox/eml/tutorial.

You will need to copy these files to a local folder. Instructions on how to copy
the files are provided in “Copying Files Locally” on page 3-4.

Names and Descriptions of Files


Type Name Description
Function emldemo_lms_01.m Baseline MATLAB implementation of
code batch filter. Not Embedded MATLAB
compliant.
emldemo_lms_01_mlint.m Baseline batch filter after elimination of
all M-Lint errors and warnings.
emldemo_lms_02.m Embedded MATLAB compliant batch
filter.

emldemo_lms_03.m Embedded MATLAB compliant batch


filter modified to accept a variable sized
input.
emldemo_lms_04.m Embedded MATLAB compliant
frame-based streaming filter.
emldemo_lms_05.m Embedded MATLAB compliant
frame-based streaming filter with Reset
and Adapt controls.

2-8
Files for This Tutorial

Type Name Description


Build emldemo_lms_build_01.m Build script for emldemo_lms_01_mlint.m.
script emldemo_lms_build_02_lib.m Build script for emldemo_lms_02.m.
Generates a C library.
emldemo_lms_build_02_mex.m Build script for emldemo_lms_02.m.
Generates a MEX function.
emldemo_lms_build_03_lib.m Build script for emldemo_lms_03.m.
Generates a C library.
emldemo_lms_build_03_mex.m Build script for emldemo_lms_03.m.
Generates a MEX function.
emldemo_lms_build_04_lib.m Build script for emldemo_lms_04.m.
Generates a C library.
emldemo_lms_build_04_mex.m Build script for emldemo_lms_04.m.
Generates a MEX function.
emldemo_lms_build_05_lib.m Build script for emldemo_lms_05.m.
Generates a C library.
emldemo_lms_build_05_mex.m Build script for emldemo_lms_05.m.
Generates a MEX function.
Test emldemo_lms_test_01.m Tests baseline M-code emldemo_lms_01.m.
script emldemo_lms_test_02.m Tests emldemo_lms_02.m and compares
output to baseline M-code.
emldemo_lms_test_03.m Tests emldemo_lms_03.m and compares
output to baseline M-code.
emldemo_lms_test_04.m Tests emldemo_lms_04.m and compares
output to baseline M-code.
emldemo_lms_test_05.m Tests emldemo_lms_05.m and compares
output to baseline M-code.
MAT-file emldemo_lms_filter.mat Contains the filter weights (or coefficients)
that are loaded by the test scripts.

2-9
2 Generating C Code from MATLAB® Code for Embedded Applications

Type Name Description


Simulink emldemo_noise_cancel_01.mdl Simulink model without an Embedded
model file MATLAB function block.
emldemo_noise_cancel_02.mdl Complete emldemo_noise_cancel_01
model including Embedded MATLAB
function block.

2-10
3

Making Your M-Code


Compliant with the
Embedded MATLAB Subset

In this part of the tutorial, you examine the LMS Filter example M-code and
make it compliant with the Embedded MATLAB subset.

• “Considerations for Making Your Code Compliant” on page 3-2


• “Making the LMS Filter Code Embedded MATLAB Compliant” on page 3-4
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

Considerations for Making Your Code Compliant


In this section...
“Designing for Compliance” on page 3-2
“Checking for Violations at Design Time” on page 3-2
“Checking for Violations at Code Generation Time” on page 3-2
“Where to Go Next” on page 3-3

Designing for Compliance


The Embedded MATLAB subset supports the embeddable subset of MATLAB
features, operators, and functions. The first step in making your MATLAB
code compliant with the Embedded MATLAB subset is to eliminate
unsupported constructs.

Checking for Violations at Design Time


You use the M-Lint code analyzer in the MATLAB Editor check for code
violations at design time, minimizing compilation errors. M-Lint continuously
checks your code as you enter it. It reports problems and recommends
modifications to maximize performance and maintainability.

To use M-Lint to identify warnings and errors specific to the Embedded


MATLAB subset, you must add the %#eml compilation directive (or pragma)
to your M-file. (You can try this in “Making the LMS Filter Code Embedded
MATLAB Compliant” on page 3-4.) A complete list of Embedded MATLAB
M-Lint messages is available in the MATLAB M-Lint preferences. See “Using
M-Lint” on page 8-7 for more details.

Checking for Violations at Code Generation Time


You can use Embedded MATLAB MEX (emlmex) to check for violations at
code generation time. emlmex checks M-code for compliance with Embedded
MATLAB syntax and semantics, as described in “Working with the Embedded
MATLAB Subset” in the Embedded MATLAB User’s Guide.

3-2
Considerations for Making Your Code Compliant

When emlmex detects errors or warnings, it automatically generates an error


report that describes the issues and provides links to the offending M-code.
See “Working with Compilation Reports” in the Embedded MATLAB User’s
Guide.

After successful compilation, emlmex generates a MEX function that you can
use to test your implementation in MATLAB.

Where to Go Next
The next section of the tutorial, “Making the LMS Filter Code Embedded
MATLAB Compliant” on page 3-4, shows you how to use M-Lint and emlmex
to make the LMS Filter code compliant with the Embedded MATLAB subset.

3-3
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

Making the LMS Filter Code Embedded MATLAB Compliant


In this section...
“Copying Files Locally” on page 3-4
“Setting Up Your C Compiler” on page 3-4
“Compiling M-Code Using emlmex” on page 3-6
“Next Task” on page 3-16
“See Also” on page 3-16
“Best Practices Used in This Section” on page 3-17

Copying Files Locally


Copy the tutorial files to a local folder:

1 Change to the matlabroot/toolbox/eml/ folder. At the MATLAB


command line, enter:

cd([matlabroot '/toolbox/eml'])

2 Create the local destination folder, for example, c:/eml/tutorial.

3 Copy the tutorial subfolder and its contents to your local folder by typing:

copyfile('tutorial', 'destination')

You are now ready to set up your C compiler.

Setting Up Your C Compiler


Before using emlmex to compile the LMS Filter example code, you must set up
your C compiler. To set up the default C compiler supplied with MATLAB:

1 At the MATLAB command line, enter:

mex -setup

The MATLAB output is:

3-4
Making the LMS Filter Code Embedded MATLAB™ Compliant

Please choose your compiler for building external


interface (MEX) files:

Would you like mex to locate installed compilers [y]/n?

2 Enter y to see the list of installed compilers.

MATLAB outputs a list of installed compilers. (The list of compilers shown


in your version of MATLAB may be different from the list shown in this
example.)

Select a compiler:
[1] Lcc-win32 C 2.4.1 in C:\PROGRA~1\MATLAB\R2008b\sys\lcc

[0] None

Compiler:

3 Enter 1 to select the default compiler.

MATLAB outputs:

Please verify your choices:

Compiler: Lcc-win32 C 2.4.1


Location: C:\PROGRA~1\MATLAB\R2008b\sys\lcc

Are these correct [y]/n?

4 Enter y to verify your choice.

The MATLAB output is:

Done . . .

You have successfully set up the C compiler.

See “Setting Up the C Compiler” in the Embedded MATLAB User’s Guide


for more information.

3-5
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

Compiling M-Code Using emlmex


You are now ready to compile your code using emlmex, which checks M-code for
compliance with Embedded MATLAB syntax and semantics, as described in
“Working with the Embedded MATLAB Subset”. After successful compilation,
emlmex generates a MEX function that you can test in MATLAB.

To begin the process of making your M-code compliant with the Embedded
MATLAB subset, you work with the file emldemo_lms_01.m.

To compile the LMS Filter code my_emldemo_lms_01.m:

1 Set your MATLAB current folder to the folder that contains your files for
this tutorial. At the MATLAB command line, enter:

cd folder

where folder is the full path name of the folder containing your files. See
“Viewing and Changing the Current Folder Using the Current Folder
Browser” in the MATLAB Desktop Tools and Development Environment
documentation for more information.

2 Open emldemo_lms_01.m in the MATLAB Editor. At the MATLAB


command line, type:

edit emldemo_lms_01.m

The M-Lint message indicator in the top right corner of the MATLAB
Editor is green, which indicates that M-Lint has not detected any errors,
warnings, or opportunities for improvement in the code.

M-Lint message
indicator
Green = no errors

3-6
Making the LMS Filter Code Embedded MATLAB™ Compliant

Note If M-Lint detects errors or warnings in your M-code, you should


resolve these issues before turning on Embedded MATLAB error checking.

3 Turn on Embedded MATLAB error checking by adding the %#eml


compilation directive after the function declaration.

function [ signal_out, err, weights ] = ...


emldemo_lms_01(distorted, desired, L) %#eml

The M-Lint message indicator remains green indicating that M-Lint has
not detected any Embedded MATLAB related issues. For more information
on using M-Lint, see “Checking M-File Code for Problems Using the
M-Lint Code Analyzer” in the MATLAB Desktop Tools and Development
documentation.

4 Save the file in the current folder as my_emldemo_lms_01.m:

a To match the function name to the file name, change the function name
to my_emldemo_lms_01.

The function signature now looks like this:

function [ signal_out, err, weights ] = ...


my_emldemo_lms_01(distorted, desired, L)

b In the MATLAB Editor, select Save As from the File menu.

c Enter my_emldemo_lms_01.m as the new file name.

Note If you do not match the filename to the function name, M-Lint
warns you that these names are not the same and highlights the function
name in orange to indicate that it can provide an automatic fix. For
more information, see “Making Changes Based on M-Lint Messages”
in the MATLAB documentation.

d Click Save.

Now you are ready to compile the LMS Filter example code using emlmex.

3-7
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

5 Because C uses static typing, emlmex must determine the properties of


all variables in the M-files at compile time. Therefore, you must specify
the properties of all function inputs at the same time as you compile the
M-file with emlmex. To compile my_emldemo_lms_01.m you need to know
the length of the audio signal that you are filtering.

To find the length of the audio sample handel.mat:


a Load the music sample stored in the file handel.mat, which is on the
MATLAB path. At the MATLAB command line, enter:

data = load('handel.mat')

The MATLAB output is:

data =
y: [73113x1 double]
Fs: 8192

data.y is a vector containing the discrete time samples of the audio


signal.data.Fs contains the sampling rate in samples per second
b Set the length of the audio sample, N, to the length of the handel.mat
audio signal. At the MATLAB command line, enter:

N = length(data.y)

The MATLAB output is:

N = 73113

c Compile the file my_emldemo_lms_01.m using emlmex. At the MATLAB


command line, enter:

emlmex my_emldemo_lms_01 -eg { zeros(N,1) zeros(N,1) 32 } ...


-o my_emldemo_lms_01_mex

emlmex reports the following error, which includes a link to the offending
line of code and a link to an error report:

??? Dimension 1 is fixed on the left-hand side but varies on


the right ([73113 x 1] ~= [:? x 1]). See documentation for
details.

3-8
Making the LMS Filter Code Embedded MATLAB™ Compliant

Error in ==> my_emldemo_lms_01 Line: 49 Column: 9


C-MEX generation failed: Open error report.
??? Error using ==> emlmex

The -eg option instructs emlmex to compile the file my_emldemo_lms_01.m


using the sample input parameters {zeros(N,1) zeros(N,1) 32}. The
-o option instructs emlmex to generate the MEX function in a file named
my_emldemo_lms_01_mex, instead of the default, which is the same as
the original M-code source file.

More About Error Reports

You can also view errors by clicking the Open error report link. The
error report provides a complete list of all the errors and warnings
detected by emlmex. You must fix the first error in the list before
addressing subsequent errors and warnings because many of these may
be related to the first error. See “Working with Compilation Reports” in
the Embedded MATLAB User’s Guide for more information.

6 Click the my_emldemo_lms_01 Line:49 Column:9 link.

The my_emldemo_lms_01 file opens with the cursor at the offending line
of code;

distorted = [ zeros(L-1,1); distorted ];

emlmex detects that you are changing the size of the array variable
distorted after it has been defined. Because you have not specified that
distorted is a variable-size array, you cannot change its size at run time.

7 Add the suffix _pad to the variable distorted on the left-hand side of the
assignment statement to create a new variable distorted_pad, which
contains the padded signal. This line of code becomes:

distorted_pad = [ zeros(L-1,1); distorted ];

The M-Lint message indicator turns orange to alert you that the file has
at least one warning. M-Lint underlines the offending code in orange and
places an orange marker to the right of it.

8 Move your pointer over the marker.

3-9
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

M-Lint detects that the value assigned to variable distorted_pad might


never be used.

M-Lint warning
message indicator.
Click indicator to
go to first warning

%#eml compilation
directive

M-Lint warning
marker.
- Hover over marker
to see message
- Click marker to go
to offending code

9 To address this warning, change the filter update loop to use the new
variable distorted_pad instead of the original variable distorted. You
need to make this change in two places: once each in the first and third
lines inside the for-loop.

The filter update loop should now look like this:

for n = 1:N
signal_out(n) = weights' * distorted_pad(n:n+L-1);
err(n) = desired(n) - signal_out(n);
weights = weights + mu*err(n)*distorted_pad(n:n+L-1);
end

3-10
Making the LMS Filter Code Embedded MATLAB™ Compliant

The orange warning marker for this line of code disappears.

The M-Lint message indicator in the top right edge of the code turns green,
which indicates that you have fixed all the errors and warnings detected by
M-Lint.

10 Save the file and compile it again. At the MATLAB command line, enter:

emlmex my_emldemo_lms_01 -eg { zeros(N,1) zeros(N,1) 32 } ...


-o my_emldemo_lms_01_mex

emlmex reports the following error, which includes a link to the offending
line of code and a link to an error report:

??? Function 'figure' implicitly resolved in the MATLAB


workspace.Implicit evaluation in MATLAB is not supported.
Please declare this function extrinsic using
eml.extrinsic('figure'), or call it using feval.
Error in ==> my_emldemo_lms_01 Line: 63 Column: 9
C-MEX generation failed: Open error report.
??? Error using ==> emlmex

11 Click the my_emldemo_lms_01 Line: 63 Column: 9 link.

The my_emldemo_lms_01 file opens with the cursor at the offending line
of code:

figure;

The Embedded MATLAB subset does not support the MATLAB function
figure. When you call an unsupported MATLAB function, you must
declare it to be extrinsic so MATLAB can execute it, but Embedded
MATLAB does not try to generate code for it.

More About Extrinsic Functions

For more information on extrinsic functions, see “Calling MATLAB


Functions” in the Embedded MATLAB User’s Guide.

3-11
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

Alternatively, you can call the figure function using feval, see “Calling
MATLAB Functions Using feval” in the Embedded MATLAB User’s Guide
for more information.

12 The functions stem , title, and num2str are also unsupported MATLAB
functions. Declare all four functions extrinsic by adding the following
declaration after the function signature:

% Declare extrinsic functions:


eml.extrinsic('figure','stem','title','num2str');

Your code should now look like this:

function [ signal_out, err, weights ] = ...


my_emldemo_lms_01(distorted, desired, L) %#eml

% Declare extrinsic functions:


eml.extrinsic('figure','stem','title','num2str');

% Version Number:
k = 1;

% Adaptation step size:


mu = 4/(32*1024);

% Signal length:
N = length(distorted);

if length(desired) == N

% Filter coefficients:
weights = zeros(L,1);

% Zero Pad Input Signal:


distorted_pad = [ zeros(L-1,1); distorted ];

% Pre-allocate output and error signals:


signal_out = zeros(N,1);
err = zeros(N,1);

% Filter Update Loop:

3-12
Making the LMS Filter Code Embedded MATLAB™ Compliant

for n = 1:N
signal_out(n) = weights' * distorted_pad(n:n+L-1);
err(n) = desired(n) - signal_out(n) ;
weights = weights + mu*err(n)*distorted_pad(n:n+L-1);
end

% Plot Impulse Response:


figure;
stem(weights);
title(['LMS Filter -- Version #' num2str(k) ...
' -- Impulse Response']);

else

error('Lengths of input signals are not equal');

end

end

13 Save the file and compile it again. At the MATLAB command line, enter:

emlmex my_emldemo_lms_01 -eg { zeros(N,1) zeros(N,1) 32 } ...


-o my_emldemo_lms_01_mex

emlmex reports the following error. Note that the line number in your error
report may not match the one shown here because you have modified the
code.

??? Computed maximum size is not bounded.


Static memory allocation requires all sizes to be bounded.
The computed size is [:? x 1].

Error in ==> my_emldemo_lms_01 Line: 47 Column: 19


C-MEX generation failed: Open error report.
??? Error using ==> emlmex

14 Click the my_emldemo_lms_01 Line:47 Column:19 link.

The my_emldemo_lms_01.m file opens with the cursor at the offending line
of code:

3-13
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

weights = zeros(L,1);

The issue: you are using the input parameter L to define the size of the
variable weights. Because you are using static array sizing, emlmex must
be able to determine the size of all array variables at code generation time.
Because the value of L is not known until run time, emlmex generates an
error.

Note The LMS filter example in this tutorial uses static array sizing.
However, the Embedded MATLAB subset supports variable-size arrays
and matrices with known upper bounds. With this feature, you can define
inputs, outputs, and local variables in Embedded MATLAB functions to
represent data that varies in size at runtime. For more information, see
“Generating Code for Variable-Size Data” in the Embedded MATLAB™
User’s Guide.

15 To fix this error, set the filter length L to a constant value:

a Remove the input parameter L.

The function signature now looks like this:

function [ signal_out, err, weights ] = ...


my_emldemo_lms_01(distorted, desired)

b Set the size of the filter length at the start of the function after the
function signature:

% Filter Length:
L = 32;

16 Save the file and compile my_emldemo_lms_01.m again, this time specifying
only two input parameters:

emlmex my_emldemo_lms_01 -eg { zeros(N,1) zeros(N,1) } ...


-o my_emldemo_lms_01_mex

3-14
Making the LMS Filter Code Embedded MATLAB™ Compliant

emlmex reports the following error. Note that the line number in your error
report may not match the one shown here because you have modified the
code.

??? Size mismatch (size [32 x 1] ~= size [:? x 1]).


Mismatched varying and fixed sizes indicate a probable
run-time error. If this diagnostic is incorrect, use
indexing to explicitly make the varying size fixed.
Error in ==> my_emldemo_lms_01 Line: 61 Column: 23
C-MEX generation failed: Open error report.
??? Error using ==> emlmex

17 Click the my_emldemo_lms_01 Line: 61 Column: 23 link.

The my_emldemo_lms_01 file opens with the cursor at the offending line
of code:

weights = weights + mu*err(n)*distorted_pad(n:n+L-1);

emlmex cannot determine the size of the expression


distorted_pad(n:n+L-1) because the values of both end points
of the array index are variables.

18 Change the matrix index expression from (n:n+L-1) to (n+(0:L-1)) so


that emlmex can determine the size of the expression.

weights = weights + mu*err(n)* distorted_pad(n+(0:L-1));

More About Matrix Indexing

For distorted_pad(n:n+L-1), the value of n and therefore the value of


n+L-1 are variables so emlmex cannot determine the size of the expression
n:n+L-1.

For distorted_pad(n+(0:L-1)), the lower and upper limits of the index


array are known so emlmex can now determine the size of L elements of
the matrix distorted_pad.

For more information, see “Using Matrix Indexing Operations” in the


Embedded MATLAB User’s Guide.

19 Make the same change for the line of code:

3-15
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

signal_out(n) = weights' * distorted_pad(n:n+L-1);

The filter update loop code should now look like this:

% Filter Update Loop:


for n = 1:N
signal_out(n) = weights' * distorted_pad(n+(0:L-1));
err(n) = desired(n) - signal_out(n) ;
weights = weights + mu*err(n)*distorted_pad(n+(0:L-1));
end

20 Save the file as my_emldemo_lms_01_compliant.m:

a To match the function name to the file name, change the function name
to my_emldemo_lms_01_compliant.
b In the MATLAB Editor, select Save As from the File menu.

c Enter my_emldemo_lms_01_compliant.m as the new file name.

d Click Save.

e Close my_emldemo_lms_01_compliant.m.

21 Compile the file my_emldemo_lms_01_compliant.m:

emlmex my_emldemo_lms_01_compliant ...


-eg { zeros(N,1) zeros(N,1) } ...
-o my_emldemo_lms_01_compliant_mex

This time emlmex compiles the file without errors or warnings.

Next Task
The LMS Filter example code is now Embedded MATLAB compliant. You are
ready to begin the next task in this tutorial, Chapter 4, “Testing Compliant
Code in MATLAB”.

See Also
• For a complete list of supported operators and programming statements,
see “Supported Operators” in the Embedded MATLAB User’s Guide.
• For a complete list of supported functions, see Embedded MATLAB
Reference.

3-16
Making the LMS Filter Code Embedded MATLAB™ Compliant

• For more information on how to call functions in the Embedded MATLAB


subset, see “Calling Functions in the Embedded MATLAB Subset” in the
Embedded MATLAB User’s Guide.
• For more information on unsupported language features, see “Unsupported
MATLAB Language Features” in the Embedded MATLAB User’s Guide.
• To learn how to use variable-size arrays and matrices, see “Generating
Code for Variable-Size Data” in the Embedded MATLAB User’s Guide.

Best Practices Used in This Section


Best Practice — Preserving Your Code
Preserve your code before making further modifications. This practice
provides a fallback in case of error and a baseline for testing and validation.
Use a consistent file naming convention. For example, add a 2-digit suffix to
the file name for each file in a sequence. See “File Naming Conventions” on
page 8-15 for more details.

Note To see the complete list of best practices used in this tutorial, see
Chapter 8, “Best Practices for Working with the Embedded MATLAB Subset”.

Best Practice — Comparing Files

Use the MATLAB Compare Against option to compare two M-files to examine
differences between files. See “Comparing Files” on page 8-9 for more
information.

Best Practice — Using the -eg Option to Specify Input Properties

Use the -eg option to specify the input properties by example. emlmex extracts
the data types and sizes of the variables listed in the cell array following
the -eg option. It is important to understand that it is not the values of the
variables that you are specifying with the -eg option, but the data types and
array dimensions of these parameters. The -eg option is easy to use, does not
alter your M-code, and is designed for prototyping a function that has a small
number of primary inputs. Alternatively, you can use the assert function to

3-17
3 Making Your M-Code Compliant with the Embedded MATLAB™ Subset

define properties of primary function inputs directly in your M-file. See “-eg
Specify Input Parameters by Example” on page 8-2 for more information.

Best Practice — Specifying an Output File Name

Use the -o option to specify an output file name for the generated MEX
function that is different from the name of the original M-file so that you can
test the M-code and MEX function and compare the results. See “-o Specify
Output File Name” on page 8-2 for more information. If you do not specify
an output file name, emlmex gives the MEX file the same name as the M-file.
It assigns a new default platform-specific file extension to the MEX file, for
example, .mexw32 for 32-bit Windows. (See “Naming Conventions” in the
Embedded MATLAB User’s Guide for more information.) If you subsequently
refer to this file by its name only (without the extension), MATLAB selects
the MEX file in accordance with file precedence rules. See “File Precedence”
in MATLAB Programming Fundamentals.

3-18
4

Testing Compliant Code in


MATLAB

In this part of the tutorial, you use a build script to generate a MEX function
for your Embedded MATLAB compliant code. You then test the MEX function
in MATLAB to verify that it is functionally equivalent to the original M-code.

• “Generating MEX Functions Using Build Scripts” on page 4-2


• “Testing MEX Functions” on page 4-5
4 Testing Compliant Code in MATLAB®

Generating MEX Functions Using Build Scripts


In this section...
“Why Use Build Scripts?” on page 4-2
“Contents of the Example Build Script” on page 4-2
“Using the Example Build Script” on page 4-3

Why Use Build Scripts?


In “Compiling M-Code Using emlmex” on page 3-6, you generated a MEX
function for your M-code by calling emlmex from the MATLAB command line.
In this part of the tutorial, you use a build script to generate your MEX
function.

Contents of the Example Build Script


The build script file emldemo_lms_build_02_mex.m supplied with this tutorial
contains.

close all;
clear all;
clc;

N = 73113;

emlmex emldemo_lms_02 -eg { zeros(N,1) zeros(N,1) } ...


-report -o emldemo_lms_02_mex

where:

• The first three commands initialize the MATLAB computing environment


in preparation for the remainder of the script.
- close all deletes all figures whose handles are not hidden. See close
in the MATLAB Graphics function reference for more information.
- clear all removes all variables, functions, and MEX-files from memory,
leaving the workspace empty. It also clears all breakpoints.

4-2
Generating MEX Functions Using Build Scripts

Note Remove the clear all command from the build scripts if you
want to preserve breakpoints for debugging.

- clc clears all input and output from the Command Window display,
giving you “clean screen”.

• N = 73113 sets the music sample size to the size of the handel.mat
audio sample. You need the audio sample length to specify the size of the
emldemo_lms_02 function input parameters. See “Compiling M-Code Using
emlmex” on page 3-6 for more information.
• emlmex is a command that:
- Compiles the file emldemo_lms_02.m, which contains the same code as
the file my_emldemo_lms_01_compliant.m that you saved at the end of
“Compiling M-Code Using emlmex” on page 3-6. You can verify that
these two files are the same by using the MATLAB Compare Against
option.
- Uses the -eg option to instruct emlmex to compile the file using the
sample input parameters { zeros(N,1) zeros(N,1) }. The -eg option
provides Embedded MATLAB with examples or prototypes of the input
variables, specifying their data types, array dimensions, and numeric
complexity but not their actual values. In this case, the prototypes are
N-by-1 vectors of all zeros represented as real-valued, double-precision
floating-point numbers.
- Uses the -report option to instruct emlmex to generate a compilation
report.
- Uses the -o option to instruct emlmex to generate the MEX function in a
file named emldemo_lms_02_mex.
See “Recommended Compilation Options for emlmex” on page 8-2 for more
information.

Using the Example Build Script


To use the build script emldemo_lms_build_02_mex.m to generate a MEX
function for emldemo_lms_02.m:

4-3
4 Testing Compliant Code in MATLAB®

1 Set your MATLAB current folder to the folder that contains your files for
this tutorial. At the MATLAB command line, enter:

cd folder

where folder is the full path name of the folder containing the files. See
“Viewing and Changing the Current Folder Using the Current Folder
Browser” in the MATLAB Desktop Tools and Development Environment
documentation for more information.

2 Run the build script by typing emldemo_lms_build_02_mex at the


MATLAB command prompt.

emlmex processes the build file and outputs the message:

C-MEX generation successful: Open coder report.

3 Verify that the output file emldemo_lms_02_mex is in the current folder.

Note The file extension you see depends on the platform on which you
are running. MATLAB adds a platform-specific file extension to the MEX
output file. for example. For example, on 32-bit Windows platforms, the
output file is emldemo_lms_02_mex.mexw32. See “Naming Conventions” in
the Embedded MATLAB User’s Guide for more information.

4-4
Testing MEX Functions

Testing MEX Functions


In this section...
“Why Use Test Scripts?” on page 4-5
“Contents of the Example Test Script” on page 4-5
“Using the Test Script” on page 4-8
“Next Task” on page 4-11
“Best Practices Used in This Section” on page 4-12

Why Use Test Scripts?


In this part of the tutorial, you test the MEX function that you generated in
“Generating MEX Functions Using Build Scripts” on page 4-2 to verify that it
provides the same functionality as the original M-code. You use a separate
test script to call your function code.

Contents of the Example Test Script


The test script emldemo_lms_test_02.m for this tutorial contains the
following sections:

Set Up
Clears your MATLAB workspace and sets the playaudio flag to true to play
the filtered audio signal at the end of the test script. If you do not want to
listen to the audio output, set the playaudio flag to false.

%% Setting up:
% Initialize:
close all;
clear all;
clc;
% Flag to play audio:
playaudio = true;

4-5
4 Testing Compliant Code in MATLAB®

Load Audio Signal


Loads the music sample from the file handel.mat, which is on the MATLAB
path. data.y is a vector containing the discrete time samples of the audio
signal, and data.Fs contains the sampling rate in samples per second.

% Load desired audio signal:


data = load('handel.mat');
desired = data.y;
Fs = data.Fs;
clear data;

Get Signal Length


Gets the length, or total number of samples, in the audio signal.

% Length of desired signal:


N = length(desired);

Set Maximum Signal Length


Sets the maximum signal length.

% Maximum signal length:


MaxLength = 128*1024;

Set Filter Length


Sets the number of samples in the filter impulse response.

% Filter length:
L = 32;

Create Distorted Signal


Generates white Gaussian noise, filters the noise using a simple low-pass
filter, and adds this bandlimited noise to the audio source to create the
distorted signal.

% samples

4-6
Testing MEX Functions

% Band-limited AWGN:
load emldemo_lms_filter.mat;
lambda = 1.0;
whiteNoise = lambda*randn(N,1);
noise = filter(b,1,whiteNoise);
% Distorted signal:
distorted = desired + noise;

Apply Original Filter


Applies the original filter emldemo_lms_01 to create a golden reference. A
golden reference provides a set of expected test results. The outputs of the
modified filter are compared to the golden reference to verify that the modified
filter is functionally equivalent to the original filter.

%% Apply LMS Filter:


% Golden reference:
[ gold.signal gold.error gold.impulse ] = ...
emldemo_lms_01(whiteNoise,distorted,L);

Apply Modified Filter


Applies the modified filter emldemo_lms_02_mex.

% Algorithm under test:


[ test.signal test.error test.impulse ] = ...
emldemo_lms_02_mex(whiteNoise,distorted);

Compare Modified Code to Original Code


Computes the differences between the output signals, error signals, and
impulse responses of the modified filter (algorithm under test) and the
original filter (golden reference.)

%% Find differences:
diff.signal = test.signal - gold.signal;
diff.error = test.error - gold.error;
diff.impulse = test.impulse - gold.impulse;

4-7
4 Testing Compliant Code in MATLAB®

What is an impulse response?

The impulse response of a system is the output of the system in response to


the application of an impulse function at its input. A discrete-time impulse
function is a sequence of zeros for all time, except at time zero, when the
impulse is exactly one.

Output Results
Plots the differences between the output signals, error signals, and impulse
responses of the two filters and plays the filtered audio signal if playaudio is
enabled.

%% Plot differences:
figure;
subplot(3,1,1);
plot(diff.signal);
title({'Algorithm Under Test versus Golden Reference'
'Output Signal'});
subplot(3,1,2);
plot(diff.error);
title('Error Signal');
subplot(3,1,3);
stem(diff.impulse);
title('Impulse Response');
%% Play sound:
if playaudio
sound(test.error);
end

Using the Test Script


To test your emldemo_lms_02_mex MEX function, type emldemo_lms_test_02
at the MATLAB command line.

As MATLAB processes the test script, you see and hear outputs. Because
playaudio is enabled, the filtered music is played. Initially, you hear the
audio signal distorted by noise. Then, during the first few seconds, the filter
attenuates the noise gradually, until you hear only the music playing with
very little noise remaining.

4-8
Testing MEX Functions

• MATLAB displays a plot of the impulse response of the original filter.

This is the golden reference, which demonstrates the expected filter


coefficients.

4-9
4 Testing Compliant Code in MATLAB®

• MATLAB displays a plot of the impulse response of the modified filter.

By comparing the impulse response of the modified filter to the golden


reference, you can see that the two outputs are nearly identical.
• MATLAB displays a plot showing the difference between the modified
filter output and the original filter output. The order of operations in the

4-10
Testing MEX Functions

Embedded MATLAB code and the MATLAB code might not be identical,
so minor differences can occur due to rounding.

These plots show that the difference between the modified filter and the
golden reference is insignificant because:
- The difference between the filter output signals is of the order 1 x 10-15.
- The difference between the filter error signals is of the order 1 x 10-15.
- The difference between the filter impulse responses is of the order 1 x
10-16 or less.
This result indicates that your Embedded MATLAB compliant filter code is
functionally equivalent to the original M-code.

Next Task
You have generated a MEX function for your Embedded MATLAB compliant
M-code and verified that it is functionally equivalent to your original M-code.

4-11
4 Testing Compliant Code in MATLAB®

Now you are ready to begin the next task in this tutorial, Chapter 5,
“Generating C Code”.

Best Practices Used in This Section


Best Practice — Using Build Scripts
Use build scripts to call emlmex. A build script automates a series of MATLAB
commands that you want to perform repeatedly from the command line,
saving you time and eliminating input errors. See “Using Build Scripts” on
page 8-5 for more information.

Best Practice — File Naming Convention

Use a consistent file naming convention, for example, include build in your
file name to indicate that this is a build script. See “File Naming Conventions”
on page 8-15 for more details.

Best Practice — Comparing Files

Use the MATLAB Compare Against option to compare two M-files to examine
differences between files. See “Comparing Files” on page 8-9 for more
information.

Best Practice — Generating a Compilation Report

Use the -report option to generate an HTML report with links to your M-code
files and compile-time type information for the variables and expressions in
your M-code. This information simplifies finding sources of error messages
and aids understanding of type propagation rules. If this option is not
specified, emlmex generates a report only if there are compilation errors or
warnings. See “-report Generate Compilation Report” on page 8-3 for more
information.

Best Practice — Separating Test Bench from Function Code

Separate your core algorithm from your test bench. Create a separate test
script to do all the pre- and post-processing such as loading inputs, setting up
input values, calling the function under test, and outputting test results.

4-12
5

Generating C Code

In this part of the tutorial, you use Embedded MATLAB Coder (emlc) to
generate C code from your Embedded MATLAB compliant code.
5 Generating C Code

Generating C Code Using emlc


In this section...
“Prerequisites for Generating C Code” on page 5-2
“Contents of the Example Build Script” on page 5-2
“Using the Example Build Script” on page 5-3
“Comparing the Generated C Code to Original M-Code” on page 5-6
“Next Task” on page 5-8
“Best Practices Used in This Section” on page 5-8

Prerequisites for Generating C Code


To use emlc, you must install Real-Time Workshop and its prerequisite
products:

• MATLAB
• Simulink
• C compiler (a default compiler is supplied with MATLAB)

For instructions on installing and setting up a C compiler, see “Setting Up the


C Compiler” in the Real-Time Workshop User’s Guide.

Contents of the Example Build Script


For this exercise, you use the build script emldemo_lms_build_02_lib.m.

emldemo_lms_build_02_lib.m contains:

close all;
clear all;
clc;

N = 73113;

emlc emldemo_lms_02 ...


-eg { zeros(N,1) zeros(N,1) } ...

5-2
Generating C Code Using emlc

-report ...
-c ...
-T rtw:lib

where:

• clear all removes all variables, functions, and MEX-files from memory,
leaving the workspace empty. It also clears all breakpoints.

Note Remove the clear all command from the build scripts if you want
to preserve break points for debugging.

• emlc opens the file emldemo_lms_02 and automatically translates the


Embedded MATLAB compliant M-code into C source code.
See “Converting MATLAB Code to C Code” in the Real-Time Workshop
User’s Guide for more information.
• The -report option instructs emlc to generate a compilation report.
• The -c option instructs emlc to generate code only, without compiling the
code to an object file.
• The -T option instructs emlc to generate embeddable C code suitable for
targeting a shared library instead of generating the default MEX function.
See emlc in the Real-Time Workshop Reference for more information.

Using the Example Build Script


To generate C code:

1 Set your MATLAB current folder to the folder that contains your files for
this tutorial.

2 Type emldemo_lms_build_02_lib at the MATLAB command prompt.

MATLAB processes the build file and outputs the message:

Compilation successful: Open compilation report.

3 To view the compilation report, click the Open compilation report. link.

5-3
5 Generating C Code

The Embedded MATLAB Compilation Report appears.

Click C-code tab to view list of


generated C files

4 Click the C-code tab to display the list of generated C files.

5-4
Generating C Code Using emlc

Click link to open C file

5-5
5 Generating C Code

5 To view the generated C code, click the link to the target source file, for
example, emldemo_lms_02.c.

The file appears in the Embedded MATLAB Coder window.

Note The generated C code is in folder\emcprj\rtwlib\emldemo_lms_02,


where folder is the folder that contains your tutorial files.

6 Close the error report and emldemo_lms_02.c file.

Comparing the Generated C Code to Original M-Code


To compare your generated C code to the original M-code, open the C file,
emldemo_lms_02.c, and the M-file, emldemo_lms_02.m, in the MATLAB
Editor. Use the left/right tile feature to view the files side by side by selecting
Window > Left/Right Tile. (See “Comparing C Code and M-Code Using
Tiling in the MATLAB Editor” on page 8-11 for more information.)

5-6
Generating C Code Using emlc

You can easily compare the generated C code to your original M-code. In
the generated C code:

• Your function name is unchanged.


• Your comments are preserved in the same position.
• Your variable names are prefixed with eml_.

Note If a variable in your M-code is set to a constant value, it does not


appear as a variable in the generated C code. Instead the generated C code
contains the actual value of the variable. For example, the variable L is
set to 32 in the M-code, so L does not appear in the generated C code, the
value 32 appears wherever L is used.

5-7
5 Generating C Code

Next Task
You have generated C code for your Embedded MATLAB compliant M-code.
You are ready to begin the next task in this tutorial, Chapter 6, “Elaborating
Your Algorithm for Embedded Implementation”.

Best Practices Used in This Section


Best Practice — Generating a Compilation Report
Use the -report option to generate an HTML report with hyperlinks to C
source files and header files automatically generated from the MATLAB
function. This information simplifies finding sources of error messages and
aids understanding of type propagation rules. If this option is not specified,
emlc generates a report only if there are compilation messages. See “-report
Generate Compilation Report” on page 8-4 for more information.

Best Practice — Generating C Code Only During Development Phase

During the development cycle, use the -c option for generating C code without
building an executable. This option enables you to iterate rapidly between
modifying M-code and generating C code. See “-c Generate Code Only” on
page 8-4 for more information.

5-8
6

Elaborating Your
Algorithm for Embedded
Implementation

In this part of the tutorial, you determine what changes you can make to your
M-code to produce more efficient, embeddable C code. This process of evolving
your M-code design is known as elaboration. It is common to iterate between
generating C code and elaborating your Embedded MATLAB compliant code
until you achieve optimal results.

• “Modifying the Filter to Accept a Variable Length Signal” on page 6-2


• “Modifying the Filter to Use Streaming” on page 6-7
• “Adding Adapt and Reset Controls” on page 6-13
• “Where to Learn More” on page 6-16
6 Elaborating Your Algorithm for Embedded Implementation

Modifying the Filter to Accept a Variable Length Signal


In this section...
“Why Modify the Filter Algorithm?” on page 6-2
“Examining the Generated C Code” on page 6-2
“Modifying Your M-Code” on page 6-3
“Generating C Code For Your Modified M-Code” on page 6-5
“Testing Your MEX Function” on page 6-6

Why Modify the Filter Algorithm?


The filter you have worked on so far in this tutorial uses a simple batch
process. This design is suitable for MATLAB, where you are likely to load
in the entire signal and process it all at once. This design is not suitable
for processing a signal in real time.

Now you are ready to modify your design to make it more suitable for
embedded implementation.

Examining the Generated C Code


One method of identifying potential improvements to the design is to examine
the generated C code. In this exercise, you examine the C code generated
in Chapter 5, “Generating C Code”.

Prerequisites
Open the file emldemo_lms_02.c which is in
folder\emcprj\rtwlib\emldemo_lms_02, where folder is the folder that
contains your tutorial files.

What to Look for in the Generated C Code


Look for code that won’t work efficiently or accurately when operating in real
time on an embedded system. For example, the use of hard-coded constants
instead of variables that can accept real-time signals.

6-2
Modifying the Filter to Accept a Variable Length Signal

Examining the C Code for the LMS Filter


In emldemo_lms_02.c, examine the function definition:

/* Function Definitions */
void emldemo_lms_02(const real_T eml_distorted[73113],
const real_T eml_desired[73113], real_T eml_signal_out[73113],
real_T eml_err[73113], real_T eml_weights[32])

The size of the input parameters eml_distorted and eml_desired are


hard-coded to a constant (73113 samples), the size of the handel.mat audio
signal. Ideally, you want to design a filter that accepts a signal of any length.
A simple first step is to modify the batch filter to accept any signal up to a
maximum size that you specify at code generation time, and then to specify
the actual signal length as an input parameter.

Modifying Your M-Code


To modify emldemo_lms_02.m to accept any signal up to a maximum size,
you preallocate maximum, fixed-size arrays for the desired and distorted
input signals at code generation time (see “Summary of Changes to the Build
Scripts” on page 6-5) and then provide a new input parameter, N, to track
the actual size of the audio sample. The value of N ensures that the filter
loop processes only valid data.

The modified filter code is supplied in emldemo_lms_03.m. The changes to


the code are in bold:

function [ signal_out, err, weights ] = ...


emldemo_lms_03(distorted, desired , N) %#eml

% Version Number:
k = 3;
% Filter Length:
L = uint32(32);
% Adaptation step-size:
mu = 4/(32*1024);
% Maximum signal length:
MaxLength = length(distorted);
% Filter coefficients:
weights = zeros(L,1);

6-3
6 Elaborating Your Algorithm for Embedded Implementation

% Zero-Pad Input Signal:


distorted_pad = [ zeros(L-1,1); distorted ];
% Pre-allocate output and error signals:
signal_out = zeros(MaxLength,1);
err = zeros(MaxLength,1);
% Filter Update Loop:
for n = 1:N
signal_out(n)=weights * distorted_pad(n+(0:L-1));
err(n)=desired(n) - signal_out(n) ;
weights=weights + mu*err(n)*distorted_pad(n+(0:L-1));
end
% Plot Impulse Response:
plotimpulse(weights,k);
end
function plotimpulse(weights,k)
% Declare extrinsic functions:
eml.extrinsic( figure , stem , title , num2str );
% Plot the impulse response of the filter weights:
figure;
stem(weights);
title([ LMS Filter -- Version # num2str(k) ...
-- Impulse Response ]);
end

Summary of Changes to the Filter Algorithm


Note the following important changes to the filter algorithm:

• The data type of the filter length L has changed from double to uint32.
You must declare L an integer because it is used in the matrix index
distorted_pad(n+(0:L-1)) where n is an integer. If L is not an integer,
a compilation error occurs.
• The new input parameter N, which contains the actual size of the audio
sample, controls the filter loop to ensure that the loop processes only valid
data:

for n = 1:N
signal_out(n) = weights' * distorted_pad(n+(0:L-1));
err(n) = desired(n) - signal_out(n) ;
weights = weights + mu*err(n)*distorted_pad(n+(0:L-1));

6-4
Modifying the Filter to Accept a Variable Length Signal

end

• The plot functions are now contained in the subfunction


plotimpulse(weights,k). It is good practice to separate your pre- and
post-processing operations (such as plotting) from your core algorithm.

More About Subfunctions

You can define subfunctions in the body of an Embedded MATLAB function


in the same way as you would in a MATLAB function. See “Calling
Subfunctions” in the Embedded MATLAB User’s Guide.

Generating C Code For Your Modified M-Code


In “Modifying the Filter to Accept a Variable Length Signal” on page 6-2,
you learned how to modify your M-code to accept any input signal up to a
maximum size. You are now ready to generate a MEX function and C code
for this new M-code.

How to Generate C Code


Follow the same procedure you used in Chapter 5, “Generating C Code” to
generate a MEX function and a C library file. To run the build scripts, enter
emldemo_lms_build_03_mex and then emldemo_lms_build_03_lib at the
MATLAB prompt.

Summary of Changes to the Build Scripts


Note the following changes to the build scripts:

• MaxLength defines the maximum size of the input signal. Set MaxLength
to a value that is greater than the biggest signal size you are likely to
encounter. In this case, MaxLength is set to a value of 131072 (128*1024)
samples.
• X = zeros(MaxLength,1) preallocates a fixed-size array using MaxLength.
X defines the properties of the desired and distorted input parameters at
code generation time.
• the –T mex option instructs emlc to generate a MEX function. See
“Recommended Compilation Options for emlc” on page 8-4 for more
information.

6-5
6 Elaborating Your Algorithm for Embedded Implementation

• –T rtw:lib option instructs emlc to generate embeddable C code and


compile it to a library (.lib file.)

Testing Your MEX Function


In this exercise, you test the MEX function that you generated in “How to
Generate C Code” on page 6-5 to verify that it provides the same functionality
as the original M-Code.

How to Test Your MEX Function


Follow the same procedure you used in “Using the Test Script” on page 4-8
with the test script emldemo_lms_test_03. The test outputs show that the
modified filter is performing in the same way as the original filter.

Summary of Changes to the Test Script


Note the following changes to the test script:

• For test purposes, the script provides the emldemo_lms_03_mex function


with input signals of length MaxLength. To create these signals, the script
zero pads the whiteNoise and distorted input signals to create two new
input signals whiteNoise_pad and distorted_pad.

whiteNoise_pad = [ whiteNoise ; zeros(MaxLength-N,1) ];


distorted_pad = [ distorted ; zeros(MaxLength-N,1) ];
[ test.signal test.error test.impulse ] = ...
emldemo_lms_03_mex(whiteNoise_pad, distorted_pad, ...
uint32(N));

• The script compares the first N elements of the output signal, which contain
the filtered audio sample, to the golden reference.

%% Find differences:
diff.signal = test.signal(1:N) - gold.signal;
diff.error = test.error(1:N) - gold.error;
diff.impulse = test.impulse - gold.impulse;

6-6
Modifying the Filter to Use Streaming

Modifying the Filter to Use Streaming


In this section...
“What Is Streaming?” on page 6-7
“Why Use Streaming?” on page 6-7
“Modifying Your M-Code” on page 6-8
“How to Generate C Code for Your Modified M-Code” on page 6-10
“How to Test Your MEX Function” on page 6-10

What Is Streaming?
A streaming filter is called repeatedly to process fixed-size chunks of input
data, or frames, until it has processed the entire input signal. The frame size
can be as small as a single sample, in which case the filter would be operating
in a sample-based mode, or up to a few thousand samples, for frame-based
processing.

Why Use Streaming?


The design of the filter algorithm in “Modifying the Filter to Accept a Variable
Length Signal” on page 6-2 has the following disadvantages:

• The algorithm does not use memory efficiently.


Preallocating a fixed amount of memory for each input signal for the
lifetime of the program means more memory is allocated than is in use.
• You must know the size of the input signal at the time you call the function.
If the input signal is arriving in real time or as a stream of samples, you
would have to wait to accumulate the entire signal before you could pass
it, as a batch, to the filter.
• The signal size is limited to a maximum size.

In an embedded application, the filter is likely to be processing a continuous


input stream. As a result, the input signal may be substantially longer than
the maximum length that a filter working in batch mode could possibly
handle. To make the filter work for any signal length, it must run in real

6-7
6 Elaborating Your Algorithm for Embedded Implementation

time. One solution is to convert the filter from batch-based processing to


stream-based processing.

Modifying Your M-Code


The conversion to streaming involves:

• Introducing a first-in, first-out (FIFO) queue.


The FIFO queue acts as a temporary storage buffer, which holds a small
number of samples from the input data stream. The number of samples
held by the FIFO queue must be exactly the same as the number of samples
in the filter’s impulse response, so that the function can perform the
convolution operation between the filter coefficients and the input signal.
• Making the FIFO queue and the filter weights persistent.
The filter is called repeatedly until it has processed the entire input signal.
Therefore, the FIFO queue and filter weights need to persist so that the
adaptation process does not have to start over again after each subsequent
call to the function.

The modified filter code is in emldemo_lms_04.m. The changes to the code


are in bold:

function [ signal_out, err, weights_out ] = ...


emldemo_lms_04(distorted, desired) %#eml

persistent weights;
persistent fifo;

% Filter length:
L = uint32(32);

% Adaptation step size:


mu = 4/(32*1024);

% Signal length:
N = length(distorted);

if length(desired) == N
if isempty(weights)

6-8
Modifying the Filter to Use Streaming

% Filter coefficients:
weights = zeros(L,1);
% FIFO Shift Register:
fifo = zeros(L,1);
end

% Pre-allocate output and error signals:


signal_out = zeros(N,1);
err = zeros(N,1);

% Filter Update Loop:


for n = 1:N
fifo(1:L-1) = fifo(2:L);
fifo(L) = distorted(n);
signal_out(n) = weights' * fifo;
err(n) = desired(n) - signal_out(n) ;
weights = weights + mu*err(n)*fifo;
end

% Output the filter weights:


weights_out = weights;
else
error('Lengths of input signals are not equal');
end
end

Summary of Changes to the Filter Algorithm


Note the following important changes to the filter algorithm:

• N is no longer an input parameter.


• The filter weights and the FIFO queue are declared as persistent:

persistent weights;
persistent fifo;

• The FIFO queue is initialized:

fifo = zeros(L,1);

6-9
6 Elaborating Your Algorithm for Embedded Implementation

• The FIFO queue is used in the filter update loop:

% Filter Update Loop:


for n = 1:N
fifo(1:L-1) = fifo(2:L);
fifo(L) = distorted(n);
signal_out(n) = weights' * fifo;
err(n) = desired(n) - signal_out(n) ;
weights = weights + mu*err(n)*fifo;
end

• You cannot output a persistent variable, therefore a new variable


weights_out is used to output the filter weights:

function [ signal_out, err, weights_out ] = ...


emldemo_lms_04(distorted, desired)

weights_out = weights;

How to Generate C Code for Your Modified M-Code


Follow the same procedure you used in Chapter 5, “Generating C Code” to
generate a MEX function and a C library file. To run the build scripts, enter
emldemo_lms_build_04_mex and then emldemo_lms_build_04_lib at the
MATLAB prompt.

Summary of Changes to the Build Scripts


The build files contain a new parameter N, which sets up the frame size. In
this case, the build script uses a value of N=2048 samples per frame for the
frame size.

How to Test Your MEX Function


Follow the same procedure you used in “Using the Test Script” on page
4-8 with the file emldemo_lms_test_04. The test outputs show that the
modified filter is performing in exactly the same way as the original filter.
The modifications for converting the filter from batch-based processing to
stream-based processing generate Embedded MATLAB compliant code that is
functionally identical to the original M-code.

6-10
Modifying the Filter to Use Streaming

Summary of Changes to the Test Script


Note the following changes to the test script:

• You must now specify the frame size and calculate the number of frames
in your audio sample:

% Frame size:
FrameSize = 2048;
% Number of frames
NumFrames = ceil(N/FrameSize);

• For test purposes, you must zero pad the input signals so that the number
of samples is an integer multiple of the frame size.

% Zero-pad:
whiteNoise = [ whiteNoise ; zeros(FrameSize*NumFrames - N,1) ];
distorted = [ distorted ; zeros(FrameSize*NumFrames - N,1) ];

• When you test the modified algorithm, you call it repeatedly (using a for-
loop) until it has processed the entire input signal:

% Algorithm under test:


for n = 0:NumFrames-1
indexRange = n*FrameSize+1:(n+1)*FrameSize;
[ yt et test.impulse ] = ...
emldemo_lms_04_mex(whiteNoise(indexRange), ...
distorted(indexRange));
test.signal(indexRange) = yt;
test.error(indexRange) = et;
end

Testing the Function with Other Audio Signals


Because the filter operates in a stream-based mode, it can process any
audio signal regardless of the number of samples the signal contains. You
can modify emldemo_lms_test_04.m to load a different audio file such as
laughter.mat (on the MATLAB path) instead of handel.mat. MATLAB
includes a total of six audio files that you can use as examples to test the
LMS function. To see the complete list, use the following command at the
MATLAB command line:

6-11
6 Elaborating Your Algorithm for Embedded Implementation

ls ([matlabroot '\toolbox\matlab\audiovideo\*.mat'])

6-12
Adding Adapt and Reset Controls

Adding Adapt and Reset Controls


In this section...
“Why Add Adapt and Reset Controls” on page 6-13
“Modifying Your M-Code” on page 6-13
“How to Generate C Code for Your Modified M-Code” on page 6-15
“How to Test Your MEX Function” on page 6-15
“Next Task” on page 6-15

Why Add Adapt and Reset Controls


In this exercise, you add Adapt and Reset controls to your filter. Using these
controls, you can turn the filtering on and off. When Adapt is enabled, the
filter continuously updates the filter weights. When Adapt is disabled, the
filter weights remain at their current values. If Reset is set, the filter resets
the filter weights.

Modifying Your M-Code


The modified filter code is in emldemo_lms_05.m. The changes to the code
are in bold:

function [ signal_out, err, weights_out ] = ...


emldemo_lms_05(distorted, desired, reset, adapt) %#eml

persistent weights;
persistent fifo;
% Filter length:
L = uint32(32);
% Adaptation step size:
mu = 4/(32*1024);
% Signal length:
N = length(distorted);
if length(desired) == N
if ( reset || isempty(weights) )
% Filter coefficients:
weights = zeros(L,1);

6-13
6 Elaborating Your Algorithm for Embedded Implementation

% FIFO Shift Register:


fifo = zeros(L,1);
end
% Pre-allocate output and error signals:
signal_out = zeros(N,1);
err = zeros(N,1);
% Filter Update Loop:
for n = 1:N
fifo(1:L-1) = fifo(2:L);
fifo(L) = distorted(n);
signal_out(n) = weights' * fifo;
err(n) = desired(n) - signal_out(n) ;
if adapt
weights = weights + mu*err(n)*fifo;
end
end
% Output the filter weights:
weights_out = weights;
else
error('Lengths of input signals are not equal');
end
end

Summary of Changes to the Filter Algorithm


Note the following important changes to the filter algorithm:

• The new input parameter reset is used to determine if it is necessary to


reset the filter coefficients:

if ( reset || isempty(weights) )
% Filter coefficients:
weights = zeros(L,1);
% FIFO Shift Register:
fifo = zeros(L,1);
end

• The new parameter adapt is used to control whether the filter coefficients
are updated or not:

6-14
Adding Adapt and Reset Controls

if adapt
weights = weights + mu*err(n)*fifo;
end

How to Generate C Code for Your Modified M-Code


Follow the same procedure you used in Chapter 5, “Generating C Code” to
generate a MEX function and a C library file. To run the build scripts, enter
emldemo_lms_build_05_mex and then emldemo_lms_build_05_lib at the
MATLAB prompt.

How to Test Your MEX Function


Follow the same procedure you used in “Using the Test Script” on page 4-8
with the file emldemo_lms_test_05. The test outputs show that the modified
filter is performing in exactly the same way as the original filter.

Summary of Changes to the Test Script


Note the following important changes to the test script:

• You must now set up the values of the Reset and Adapt controls before
using the filter. In this test, the controls are set so that the filter is
constantly adapting:

reset = false;
adapt = true;

• You pass in the values of Reset and Adapt when you call the filter:

[ yt et test.impulse ] = ...
emldemo_lms_05_mex(whiteNoise(indexRange), ...
distorted(indexRange), reset, adapt);

Next Task
If you want to integrate your M-code with Simulink, perform the second
procedure in this tutorial, Chapter 7, “Integrating Your Embedded MATLAB
Compliant Code with Simulink”.

6-15
6 Elaborating Your Algorithm for Embedded Implementation

Where to Learn More


In this section...
“Next Steps” on page 6-16
“Product Help” on page 6-17
“The MathWorks Online” on page 6-17

Next Steps
To... See...

Learn more about using the Embedded Embedded MATLAB™ User’s Guide
MATLAB subset
Speed up fixed-point M-code “Working with Embedded MATLAB MEX” in
the Real-Time Workshop User’s Guide
Integrate custom C code into MATLAB and “Converting MATLAB Code to C Code” in the
generate embeddable code Embedded MATLAB User’s Guide
Integrate custom C code into an Embedded eml.ceval in the Embedded MATLAB
MATLAB function Reference
Generate HDL from M-code www.mathworks.com/products/slhdlcoder

Learn more about the best practices used in Chapter 8, “Best Practices for Working with
this tutorial the Embedded MATLAB Subset”

6-16
Where to Learn More

Product Help
The MathWorks technical documentation is available online from the Help
menu on the MATLAB desktop.

For... See...
Embedded MATLAB subset usage “Working with the Embedded
MATLAB Subset” in the Embedded
MATLAB User’s Guide
A list of Embedded MATLAB Embedded MATLAB Reference
functions
What’s new Embedded MATLAB™ Release Notes

The MathWorks Online


For additional information and support, visit the
Embedded MATLAB page on the MathWorks web site at:
www.mathworks.com/products/featured/embeddedmatlab

6-17
6 Elaborating Your Algorithm for Embedded Implementation

6-18
7

Integrating Your Embedded


MATLAB Compliant Code
with Simulink

• “Tasks for Integrating with Simulink” on page 7-2


• “Integrating with Simulink” on page 7-3
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

Tasks for Integrating with Simulink


Here is a flow chart showing the tasks for integrating Embedded MATLAB
compliant code with Simulink using the Embedded MATLAB function block:

The first part of this tutorial guided you through the tasks for generating C
code from your M-code. This part of the tutorial guides you through the steps
involved in integrating your M-code with Simulink. You may integrate your
M-code with Simulink either after making it compliant with the Embedded
MATLAB subset or after generating C code.

To learn more about making your M-code compliant with the Embedded
MATLAB subset, see Chapter 3, “Making Your M-Code Compliant with the
Embedded MATLAB Subset”.

To learn more about the tasks for generating C code, see “Tasks For
Generating C Code” on page 2-2.

7-2
Integrating with Simulink®

Integrating with Simulink


In this section...
“Introduction” on page 7-3
“Files Supplied with This Tutorial” on page 7-4
“Adding an Embedded MATLAB Function Block to Your Model” on page 7-4
“Calling Your M-Code from the Embedded MATLAB Function Block” on
page 7-7
“Connecting the Embedded MATLAB Function Block Inputs and Outputs”
on page 7-8
“Configuring Embedded MATLAB Outputs” on page 7-10
“Running the emldemo_noise_cancel_01 Model” on page 7-11
“Using eml.extrinsic to Debug Your M-Code” on page 7-14
“Next Steps” on page 7-15
“Best Practice Used in This Section” on page 7-15

Introduction

7-3
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

This part of the tutorial demonstrates how to integrate M-code into Simulink
using the Embedded MATLAB Function block. The Embedded MATLAB
Function block allows you to add MATLAB functions to Simulink models
for simulation, testing, code generation, and/or deployment to embedded
processors. It supports a subset of MATLAB commands that generate efficient
C code.

Files Supplied with This Tutorial


To begin the process of integrating your M-code with Simulink, you work with
the model emldemo_noise_cancel_01.mdl and the file emldemo_lms_05.m.
Alternatively, you can view the changes described in this part of the tutorial
in the model emldemo_noise_cancel_02.mdl.

The file emldemo_lms_05.m implements a least mean squares (LMS) filter. The
models emldemo_noise_cancel_01.mdl and emldemo_noise_cancel_02.mdl
use this filter to remove noise from an input signal. For more information, see
“Example: The LMS Filter” on page 2-4.

Note If you have not already copied these files to a local folder, follow the
instructions in “Copying Files Locally” on page 3-4.

Adding an Embedded MATLAB Function Block to Your


Model
In practice, you would add an Embedded MATLAB Function Block to an
empty model, and then add input and output blocks as required. To simplify
this process for the purposes of this tutorial, you add the Embedded MATLAB
Function Block to the emldemo_noise_cancel_01 model supplied with the
tutorial.

To add an Embedded MATLAB Function block to the


emldemo_noise_cancel_01 model:

1 Open emldemo_noise_cancel_01.mdl in Simulink:

a Set your MATLAB current folder to the folder that contains your files for
this tutorial. At the MATLAB command line, enter:

7-4
Integrating with Simulink®

cd folder

where folder is the full path name of the folder containing your files.
See “Viewing and Changing the Current Folder Using the Current
Folder Browser” in the MATLAB Desktop Tools and Development
Environment documentation for more information.
b At the MATLAB command line, type:

emldemo_noise_cancel_01

The model opens:

2 Add an Embedded MATLAB Function block to the model:

a At the MATLAB command line, type simulink to open the Simulink


library browser.

7-5
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

b From the list of Simulink libraries, select the User-Defined Functions


library.
c Click the Embedded MATLAB Function block and drag it into the
emldemo_noise_cancel_01 model. Place the block just above the red
text annotation Place Embedded MATLAB Function Block here.

Your model should now look like this:

d Delete the red text annotations from the model.

e Save the model in the current folder as


my_emldemo_noise_cancel_01.mdl.
i In the Simulink Model Editor, select Save As from the File menu.
ii Enter my_emldemo_noise_cancel_01.mdl as the new model name.
iii Click Save.

7-6
Integrating with Simulink®

Calling Your M-Code from the Embedded MATLAB


Function Block
You now use the Embedded MATLAB Function block to call your existing
function emldemo_lms_05. To add your M-code to the Embedded MATLAB
Function block:

1 Double-click the Embedded MATLAB Function block to open the Embedded


MATLAB editor.

2 Delete the default code displayed in the Embedded MATLAB editor.

3 Copy the following code to the Embedded MATLAB Function block.

function [ Signal_Out, Weights ] = ...


LMS(Adapt, Reset, Noise_In, Signal_In) %#eml

% Compute LMS:
[ ~, Signal_Out, Weights ] = ...
emldemo_lms_05(Noise_In, Signal_In, Reset, Adapt);

end

Because the LMS function does not use the first output from
emldemo_lms_05, replace this output with the MATLAB ~ operator.
Embedded MATLAB ignores inputs and outputs specified by ~. This syntax
helps avoid confusion in your program code and unnecessary clutter in
your workspace.

Note You can use the eml.extrinsic function to call your M-code. Using
eml.extrinsic enables you to debug your M-code in MATLAB. For more
information, see Using eml.extrinsic to Debug Your M-Code.

4 Resize the Embedded MATLAB Function block. The emldemo_lms_05


function inputs Noise_In, Signal_In, Reset and Adapt now appear as

7-7
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

input ports to the block and the function outputs Signal_Out and Weights
appear as output ports.

5 Save the model by selecting File > Save from the Embedded MATLAB
editor menu.

Connecting the Embedded MATLAB Function Block


Inputs and Outputs
The next step is to connect the Embedded MATLAB function block inputs
and outputs.

7-8
Integrating with Simulink®

Make the following connections:

From... To...
Settings > Adapt Embedded MATLAB Function Block
> Adapt
Settings > Reset Embedded MATLAB Function Block
> Reset
White Noise Embedded MATLAB Function Block
> Noise_In
Acoustic_Environment > Signal_Out Embedded MATLAB Function Block
> Signal_In
Embedded MATLAB Function Block To Audio Device
> Signal_Out
Embedded MATLAB Function Block Analysis and Visualization > Signal
> Signal_Out
Embedded MATLAB Function Block Analysis and Visualization >
> Weights Weights

See “Connecting Blocks” in the Simulink documentation for more information.

7-9
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

Your model should now look like this:

Configuring Embedded MATLAB Outputs


Because the Analysis and Visualization block expects to receive a frame-based
signal from the LMS filter, you must configure the Embedded MATLAB
Function block Signal_Out output parameter to be frame-based rather than
sample-based.

1 Double-click the Embedded MATLAB Function block to open the Embedded


MATLAB editor.

2 Select Tools > Edit Data/Ports to open the Ports and Data Manager.

3 Select the signal called Signal_Out from the list in the left pane.

7-10
Integrating with Simulink®

4 On the General tab, change the Sampling mode from Sample based
to Frame based.

Click the Apply button.

5 Close the Ports and Data Manager and the Embedded MATLAB editor.

6 Save the model.

You are now ready to run the model.

Running the emldemo_noise_cancel_01 Model


To run the model:

1 Ensure that you can see the Time Domain plots.

To view the plots, in the emldemo_noise_cancel_01 model, open the


Analysis and Visualization block and then open the Time Domain block.

7-11
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

2 Select Simulation > Start in the Simulink model window.

While the model is running, you can double-click the Reset and Adapt
settings to control the operation of the filter. When Adapt is enabled, the
filter continuously updates the filter weights. When Adapt is disabled, the
filter weights remain at their current values. If Reset is set, the filter
resets the filter weights.

For standard operation, you should enable the Adapt signal and disable
the Reset signal.

As Simulink runs the model, you see and hear outputs. Initially, you hear
the audio signal distorted by noise. Then, during the first few seconds,
the filter attenuates the noise gradually, until you hear only the music
playing with very little noise remaining. MATLAB displays the following
plot showing filter convergence after only a few seconds.

7-12
Integrating with Simulink®

7-13
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

Using eml.extrinsic to Debug Your M-Code


You can use the eml.extrinsic function to call your M-code. Using
eml.extrinsic enables you to debug your M-code in MATLAB. You can
add one or more breakpoints in the file emldemo_lms_05.m, and then start
the simulation in Simulink. When the MATLAB interpreter encounters
a breakpoint, it temporarily halts execution so that you can inspect the
MATLAB Workspace and view the current values of all variables in memory.
For more information about debugging M-code, see “Editing and Debugging
M-Files” in the MATLAB documentation.

To use eml.extrinsic:

1 Double click the Embedded MATLAB Function block to open the Embedded
MATLAB editor.

2 Delete the code displayed in the Embedded MATLAB editor.

3 Copy the following code to the Embedded MATLAB Function block:

function [ Signal_Out, Weights ] = ...


LMS(Adapt, Reset, Noise_In, Signal_In) %#eml

%Declare emldemo_lms_05 extrinsic


eml.extrinsic('emldemo_lms_05');
FilterLength = 32;

%Preallocate memory for Weights and Signal_Out


%because emldemo_lms_05 is extrinsic
Weights = zeros(FilterLength,1);
Signal_Out = Signal_In;

% Compute LMS:
[ ~, Signal_Out, Weights ] = ...
emldemo_lms_05(Noise_In, Signal_In, Reset, Adapt);
end

7-14
Integrating with Simulink®

Next Steps
To... See...

Learn more about using the Embedded “Using the Embedded MATLAB Function
MATLAB Function block Block” in the Simulink User’s Guide
Learn more about the best practices used in Chapter 8, “Best Practices for Working with
this tutorial the Embedded MATLAB Subset”

Best Practice Used in This Section


Best Practice — Saving Incremental Code Updates
Save your code before making further modifications. This practice provides
a fallback in case of error and a baseline for testing and validation. Use a
consistent file naming convention. For example, add a 2-digit suffix to the file
name for each file in a sequence. See “File Naming Conventions” on page
8-15 for more details.

Note To see the complete list of best practices used in this tutorial, see
Chapter 8, “Best Practices for Working with the Embedded MATLAB Subset”.

7-15
7 Integrating Your Embedded MATLAB™ Compliant Code with Simulink®

7-16
8

Best Practices for Working


with the Embedded
MATLAB Subset

• “Recommended Compilation Options for emlmex” on page 8-2


• “Recommended Compilation Options for emlc” on page 8-4
• “Using Build Scripts” on page 8-5
• “Using M-Lint” on page 8-7
• “Separating Your Test Bench from Your Function Code” on page 8-8
• “Comparing Files” on page 8-9
• “Testing MEX Functions in MATLAB” on page 8-13
• “Preserving Your Code” on page 8-14
• “File Naming Conventions” on page 8-15
8 Best Practices for Working with the Embedded MATLAB™ Subset

Recommended Compilation Options for emlmex


In this section...
“-eg Specify Input Parameters by Example” on page 8-2
“-o Specify Output File Name” on page 8-2
“-report Generate Compilation Report” on page 8-3

-eg Specify Input Parameters by Example


Use the -eg option to specify the properties of primary function inputs as a
cell array of example values at the same time as you compile the M-file with
emlmex. The cell array can be a variable or literal array of constant values.
The cell array should provide the same number and order of inputs as the
primary function. It is important to understand that it is not the values of the
variables that you are specifying with the -eg option, but the data types and
array dimensions of these parameters.

For more information, see “Defining Input Properties by Example at the


Command Line” in the Embedded MATLAB User’s Guide.

Note Alternatively, you can use the assert function to define properties
of primary function inputs directly in your M-file. See “Defining Input
Properties Programmatically in the M-File” in the Embedded MATLAB User’s
Guide for more information.

-o Specify Output File Name


Use the -o option to specify an output file name for the generated MEX
function that is different from the name of the original M-file. This practice
lets you test the M-code and MEX function and compare the results. If you do
not specify an output file name, emlmex gives the MEX file the same name
as the M-file and assigns a new default platform-specific file extension, for
example, .mexw32 for 32-bit Windows. (See “Naming Conventions” in the
Embedded MATLAB User’s Guide for more information.) If you subsequently
refer to this file by its name only (without the extension), MATLAB selects

8-2
Recommended Compilation Options for emlmex

the MEX file in accordance with file precedence rules. See “File Precedence”
in MATLAB Programming Fundamentals.

For more information, see “-o Specify Output File Name” in the Embedded
MATLAB Reference.

For a complete list of compilation options, see emlmex in the Embedded


MATLAB Reference.

-report Generate Compilation Report


Use the -report option to generate a compilation report in HTML format at
compile time to help you debug your M-code and verify compliance with the
Embedded MATLAB subset. If the -report option is not specified, emlmex
generates a report only if there are compilation errors or warnings.

The compilation report contains the following information:

• Summary of compilation results, including type of target and number of


warnings or errors
• Target build log that records compilation and linking activities
• Links to generated files
• Error and warning messages (if any)

For more information, see emlmex in the Embedded MATLAB Reference.

8-3
8 Best Practices for Working with the Embedded MATLAB™ Subset

Recommended Compilation Options for emlc


In this section...
“-c Generate Code Only” on page 8-4
“-report Generate Compilation Report” on page 8-4

-c Generate Code Only


Use the -c option to generate code only without invoking the make command.
If this option is used, emlc does not generate compiled object code. This option
saves you time during the development cycle when you want to iterate rapidly
between modifying M-code and generating C code and are mainly interested
in inspecting the C code. Use this option only for rtw, rtw:exe, and rtw:lib
targets.

For more information and a complete list of compilation options, see emlc in
the Real-Time Workshop Reference.

-report Generate Compilation Report


Use the -report option to generate a compilation report in HTML format
at compile time to help you debug your M-code and verify compliance with
the Embedded MATLAB subset. If the -report option is not specified, emlc
generates a report only if there are compilation errors or warnings.

The compilation report contains the following information:

• Summary of compilation results, including type of target and number of


warnings or errors
• Target build log that records compilation and linking activities
• Links to generated files
• Error and warning messages (if any)

For more information, see emlc in the Real-Time Workshop Reference.

8-4
Using Build Scripts

Using Build Scripts


Use build scripts to call emlmex or emlc to generate C code from your
Embedded MATLAB function.

A build script automates a series of MATLAB commands that you want to


perform repeatedly from the command line, saving you time and eliminating
input errors. For instance, you can use a build script to clear your workspace
before each build and to specify compiler options.

Here is an example of a build script to run emlc to process emldemo_lms_02.m:

close all;
clear all;
clc;

N = 73113;

emlc emldemo_lms_02 ...


-eg { zeros(N,1) zeros(N,1) } ...
-report ...
-c ...
-T rtw:lib

where:

• close all deletes all figures whose handles are not hidden. See close in
the MATLAB Graphics function reference for more information.
• clear all removes all variables, functions, and MEX-files from memory,
leaving the workspace empty. It also clears all breakpoints.

Note Remove the clear all command from the build scripts if you want
to preserve breakpoints for debugging.

• clc clears all input and output from the Command Window display, giving
you a “clean screen.”

8-5
8 Best Practices for Working with the Embedded MATLAB™ Subset

• N = 73113 sets the value of the variable N, which represents the


number of samples in each of the two input parameters for the function
emldemo_lms_02
• emlc emldemo_lms_02 -eg { zeros(N,1) zeros(N,1) } -report -o
emldemo_lms_02_mex -T mex calls emlc to compile file emldemo_lms_02
using the following compilation options:
- -eg { zeros(N,1) zeros(N,1) } specifies the properties of the
function inputs as a cell array of example values. In this case, the input
parameters are N-by-1 vectors of real doubles.
- -report generates a compilation report
- -o emldemo_lms_02_mex specifies the output file name as
emldemo_lms_02_mex
- -T mex specifies the target as a MEX function

8-6
Using M-Lint

Using M-Lint

Using M-Lint to Check Code Interactively at Design


Time
The M-Lint code analyzer checks your code for problems and recommends
modifications to maximize performance and maintainability. You can use
M-Lint to check your code continuously in the MATLAB Editor while you
work.

To ensure that continuous code checking is enabled:

1 From the MATLAB menu, select File > Preferences > M-Lint.

The list of M-Lint preferences appears.

2 Select the Enable integrated M-Lint warning and error messages


check box.

8-7
8 Best Practices for Working with the Embedded MATLAB™ Subset

Separating Your Test Bench from Your Function Code


Separate your core algorithm from your test bench. Create a separate test
script to do all the pre- and post-processing such as loading inputs, setting up
input values, calling the function under test, and outputting test results.

8-8
Comparing Files

Comparing Files
In this section...
“Comparing Two Versions of a File Using the MATLAB Compare Against
Option” on page 8-9
“Comparing C Code and M-Code Using Tiling in the MATLAB Editor” on
page 8-11

Comparing Two Versions of a File Using the MATLAB


Compare Against Option
Use the MATLAB Compare Against option to compare two different versions
of the same file. This option launches the File and Folder Comparison Tool,
which displays the two files side by side and highlights lines that do not match.

To compare two files:

1 Open one of the files you want to compare in the MATLAB Editor.

2 Select Tools > Compare Against > Browse. Navigate to the file you
want to compare against, select the file, and click Open.

The File and Folder Comparison tool opens, displaying the files side by side
and highlighting lines that do not match:
• Pink highlighting and an x at the start of a line indicate that the content
of the lines differs between the two files.
• Green highlighting and a > at the start of a line indicate a line that exists
in the file presented on the right, but not in the file presented on the left.
• Green highlighting and a < at the end of a line indicate a line that exists
in the file presented on the left, but not in the file presented on the right.

8-9
8 Best Practices for Working with the Embedded MATLAB™ Subset

Differences between the files emldemo_lms_02.m and emldemo_lms_03.m


are highlighted in the following figure. These files are in the
matlabroot/toolbox/eml/tutorial folder for the tutorial in the
Embedded MATLAB Getting Started Guide.

For more information, see “Comparing Files and Folders” in the MATLAB
Desktop Tools and Development Environment documentation.

8-10
Comparing Files

Comparing C Code and M-Code Using Tiling in the


MATLAB Editor
Use the MATLAB Editor’s left/right tile feature to compare your generated
C code to the original M-code. You can easily compare the generated C code
to your original M-code. In the generated C code:

• Your function name is unchanged.


• Your variable names are prefixed with eml_.
• Your comments are preserved in the same position.

To compare two files, follow these steps:

1 Open the C file and the M-file in the Editor. (Dock both windows if they
are not docked.)

2 Select Window > Left/Right Tile (or the toolbar button) to view
the files side by side.

8-11
8 Best Practices for Working with the Embedded MATLAB™ Subset

The M-file emldemo_lms_02.m and its generated C code emldemo_lms_02.c


are displayed in the following figure. The file emldemo_lms_02.m is supplied
in the matlabroot/toolbox/eml/tutorial folder for use with the Embedded
MATLAB getting started tutorial.

8-12
Testing MEX Functions in MATLAB®

Testing MEX Functions in MATLAB


For rapid prototyping before you generate C code, use emlmex (or, if you have
Real-Time Workshop, emlc with the -T mex option) to convert your M-code to
a MEX function. emlmex generates a platform-specific MEX-file, which you
can execute within the MATLAB environment to test your algorithm.

For more information, see emlmex in the Embedded MATLAB Function


Reference or emlc in the Real-Time Workshop Reference.

8-13
8 Best Practices for Working with the Embedded MATLAB™ Subset

Preserving Your Code


Preserve your code before making further modifications. This practice
provides a fallback in case of error and a baseline for testing and validation.
Use a consistent file naming convention. For example, add a 2-digit suffix to
the file name for each file in a sequence. See “File Naming Conventions” on
page 8-15 for more details.

8-14
File Naming Conventions

File Naming Conventions


Use a consistent file naming convention to identify different types and
versions of your M-files. This approach keeps your files organized and
minimizes the risk of overwriting existing files or creating two files with the
same name in different directories.

For example, the file naming convention in the Embedded MATLAB getting
started tutorial is:

• The suffix _build identifies a build script.


• The suffix _test identifies a test script.
• A numerical suffix, for example, _01 identifies the version of a file. These
numbers are typically two-digit sequential integers, beginning with 01,
02, 03, and so on.

For example:

• The file emldemo_lms_build_01.m is the first version of the build script


for this tutorial.
• The file emldemo_lms_test_03.m is the third version of the test script
for this tutorial.

8-15
8 Best Practices for Working with the Embedded MATLAB™ Subset

8-16
Index

C
Index getting started tutorial prerequisites 1-8
C compiler integrating compliant code with
set up for Embedded MATLAB 3-4 Simulink 7-2
code generation making code compliant 3-2
converting MATLAB code to embeddable C MEX functions 4-2
code 2-2 recommended compilation options for
emlc 8-4
recommended compilation options for
D emlmex 8-2
design considerations test scripts 4-5
for generating embeddable C code from testing MEX functions 4-5
MATLAB code 2-3 using emlc 5-2
using emlmex 3-6
using M-Lint 3-2
E
when not to use 1-6
elaboration when to use 1-3
Embedded MATLAB code 6-2 Embedded MATLAB compliant code
Embedded MATLAB integrating with Simulink 7-2
benefits of 1-7 embedded MATLAB function block
best practices calling M-code 7-7
comparing files 3-17 4-12 8-9 Embedded MATLAB function block
generate C code only 8-4 using 7-4
generate compilation report 8-3 to 8-4 eml.extrinsic
preserving your code 8-14 using to debug M-code 7-14
separating test bench from function emlc
code 8-8 recommended compilation options 8-4
specifying input properties 3-17 8-2 emlmex
specifying output file name 3-18 8-2 recommended compilation options 8-2
testing MEX functions in MATLAB 8-13
using build scripts 4-12 8-5
using file naming convention 4-12 8-15 G
using M-Lint 8-7 generating code
using test scripts 4-12 converting MATLAB code to embeddable C
C code generation 2-2 code 2-2
C compiler set up 3-4
compliance 3-2
I
description 1-2
elaborating code 6-2 integrating M-code with Simulink
features 1-4 Embedded MATLAB 7-2
generating C code 5-2

Index-1
Index

M T
M-Lint testing
using with Embedded MATLAB 3-2 Embedded MATLAB compliant code 4-5

Index-2

You might also like