当前位置:首页 >> 工学 >>

Code Generation from MATLAB User's Guide R2011B


Code Generation from MATLAB? User’s Guide

R2011b

How to Contact MathWorks

Web Newsgroup www.mathworks.com/contact_TS.html Technical Support
www.mathworks.com comp.soft-sys.matlab suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.com info@mathworks.com

Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes 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. Code Generation from MATLAB User’s Guide ? COPYRIGHT 2007–2011 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc. FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government’s needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.

Trademarks

MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders.
Patents

MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for more information.

Revision History

March 2007 September 2007 March 2008 October 2008 March 2009 September 2009 March 2010 September 2010 April 2011 September 2011

Online Online Online Online Online Online Online Online Online Online

only only only only only only only only only only

New for Release 2007a Revised for Release 2007b Revised for Release 2008a Revised for Release 2008b Revised for Release 2009a Revised for Release 2009b Revised for Release 2010a Revised for Release 2010b Revised for Release 2011a Revised for Release 2011b

Contents
About Code Generation from MATLAB Algorithms

1
Direct Translation of MATLAB Algorithms to C/C++ Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Prerequisites for Code Generation from MATLAB . . . . Preparing MATLAB Code for C/C++ and MEX Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Expected Differences in Behavior After Compiling Your MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Why Are There Differences? . . . . . . . . . . . . . . . . . . . . . . . . . Character Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Order of Evaluation in Expressions . . . . . . . . . . . . . . . . . . . Termination Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Size of Variable-Size N-D Arrays . . . . . . . . . . . . . . . . . . . . . Floating-Point Numerical Results . . . . . . . . . . . . . . . . . . . . NaN and Infinity Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Language Features Supported for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Language Features Not Supported for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Related Products That Support Code Generation from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1-3

1-4

1-5 1-5 1-5 1-5 1-6 1-6 1-7 1-7 1-7

1-9

1-11

1-12

v

Functions Supported for Code Generation

2
About Code Generation for Supported Functions . . . . . Functions Supported for Code Generation — Alphabetical List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Functions Supported for Code Generation — Categorical List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Aerospace Toolbox Functions . . . . . . . . . . . . . . . . . . . . . . . . Arithmetic Operator Functions . . . . . . . . . . . . . . . . . . . . . . Bit-Wise Operation Functions . . . . . . . . . . . . . . . . . . . . . . . Casting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Communications System Toolbox Functions . . . . . . . . . . . . Complex Number Functions . . . . . . . . . . . . . . . . . . . . . . . . . Computer Vision System Toolbox Functions . . . . . . . . . . . . Data Type Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Derivative and Integral Functions . . . . . . . . . . . . . . . . . . . . Discrete Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . Error Handling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . Exponential Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Filtering and Convolution Functions . . . . . . . . . . . . . . . . . . Fixed-Point Toolbox Functions . . . . . . . . . . . . . . . . . . . . . . . Histogram Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Image Processing Toolbox Functions . . . . . . . . . . . . . . . . . . Input and Output Functions . . . . . . . . . . . . . . . . . . . . . . . . Interpolation and Computational Geometry . . . . . . . . . . . . Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Logical Operator Functions . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Compiler Functions . . . . . . . . . . . . . . . . . . . . . . . Matrix and Array Functions . . . . . . . . . . . . . . . . . . . . . . . . . Nonlinear Numerical Methods . . . . . . . . . . . . . . . . . . . . . . . Polynomial Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Relational Operator Functions . . . . . . . . . . . . . . . . . . . . . . . Rounding and Remainder Functions . . . . . . . . . . . . . . . . . . Set Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Signal Processing Functions in MATLAB . . . . . . . . . . . . . . Signal Processing Toolbox Functions . . . . . . . . . . . . . . . . . . Special Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specialized Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Statistical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 2-3

2-59 2-60 2-60 2-61 2-61 2-62 2-62 2-63 2-64 2-64 2-64 2-65 2-65 2-66 2-66 2-75 2-75 2-76 2-76 2-77 2-77 2-78 2-78 2-82 2-82 2-82 2-83 2-83 2-84 2-84 2-89 2-89 2-90

vi

Contents

String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Structure Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-90 2-91 2-91

System Objects Supported for Code Generation

3
About Code Generation for System Objects . . . . . . . . . . Computer Vision System Toolbox System Objects Communications System Toolbox System Objects 3-2 3-3 3-7 3-13

.... ....

DSP System Toolbox System Objects . . . . . . . . . . . . . . . .

Defining MATLAB Variables for C/C++ Code Generation

4
Why Define Variables Differently for Code Generation? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Best Practices for Defining Variables for C/C++ Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Define Variables By Assignment Before Using Them . . . . Use Caution When Reassigning Variables . . . . . . . . . . . . . Use Type Cast Operators in Variable Definitions . . . . . . . . Define Matrices Before Assigning Indexed Variables . . . . . When You Can Reassign Variable Properties for C/C++ Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Eliminating Redundant Copies of Variables in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2

4-3 4-3 4-6 4-6 4-6

4-7

4-8

vii

When Redundant Copies Occur . . . . . . . . . . . . . . . . . . . . . . How to Eliminate Redundant Copies by Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . Defining and Initializing Persistent Variables . . . . . . . . Reusing the Same Variable with Different Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . When You Can Reuse the Same Variable with Different Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . When You Cannot Reuse Variables . . . . . . . . . . . . . . . . . . . Limitations of Variable Reuse . . . . . . . . . . . . . . . . . . . . . . . Supported Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . .

4-8 4-8 4-9 4-10

4-11 4-11 4-12 4-14 4-16

Defining Data for Code Generation

5
How Working with Data is Different for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation for Complex Data . . . . . . . . . . . . . . . . . Restrictions When Defining Complex Variables . . . . . . . . . Expressions Containing Complex Operands Yield Complex Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation for Characters . . . . . . . . . . . . . . . . . . . . 5-2 5-4 5-4 5-5 5-6

Code Generation for MATLAB Structures

6
How Working with Structures Is Different for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2

viii

Contents

Structure Operations Allowed for Code Generation . . . Defining Scalar Structures for Code Generation . . . . . . Restrictions When Using struct . . . . . . . . . . . . . . . . . . . . . Restrictions When Defining Scalar Structures by Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding Fields in Consistent Order on Each Control Flow Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Restriction on Adding New Fields After First Use . . . . . . . Defining Arrays of Structures for Code Generation . . . Ensuring Consistency of Fields . . . . . . . . . . . . . . . . . . . . . . Using repmat to Define an Array of Structures with Consistent Field Properties . . . . . . . . . . . . . . . . . . . . . . . Defining an Array of Structures Using Concatenation . . . . Making Structures Persistent . . . . . . . . . . . . . . . . . . . . . . . Indexing Substructures and Fields . . . . . . . . . . . . . . . . . . Assigning Values to Structures and Fields . . . . . . . . . . . Passing Large Structures as Input Parameters . . . . . . .

6-3 6-4 6-4 6-4 6-4 6-5 6-7 6-7 6-7 6-8 6-9 6-10 6-12 6-13

Code Generation for Enumerated Data

7
How Working with Enumerated Data Is Different for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Enumerated Types Supported for Code Generation . . . Enumerated Type Based on int32 . . . . . . . . . . . . . . . . . . . . Enumerated Type Based on Simulink.IntEnumType . . . . . When to Use Enumerated Data for Code Generation . . 7-2 7-2 7-3 7-3 7-4 7-6

ix

Workflows for Using Enumerated Data for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Workflow for Generating Code for Enumerated Data from MATLAB Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . Workflow for Generating Code for Enumerated Data from MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . How to Define Enumerated Data for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Naming Enumerated Types for Code Generation . . . . . . . . How to Instantiate Enumerated Types for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How to Generate Code for Enumerated Data . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining and Using Enumerated Types for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Class Definition: sysMode . . . . . . . . . . . . . . . . . . . . . . . . . . Class Definition: LEDcolor . . . . . . . . . . . . . . . . . . . . . . . . . . Function: displayState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Operations on Enumerated Data Allowed for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Assignment Operator, = . . . . . . . . . . . . . . . . . . . . . . . . . . . . Relational Operators, < > <= >= == ~= . . . . . . . . . . . . . . . . Cast Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Indexing Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Control Flow Statements: if, switch, while . . . . . . . . . . . . . Using Enumerated Data in Control Flow Statements . . Using the if Statement on Enumerated Data Types . . . . . Using the switch Statement on Enumerated Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the while Statement on Enumerated Data Types . . Restrictions on Use of Enumerated Data in for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7-7 7-7 7-8

7-9 7-10

7-11 7-12 7-12

7-13 7-13 7-13 7-14 7-14

7-15 7-15 7-15 7-16 7-16 7-17 7-18 7-18 7-19 7-22

7-24

x

Contents

Toolbox Functions That Support Enumerated Types for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-25

Code Generation for Variable-Size Data

8
What Is Variable-Size Data? . . . . . . . . . . . . . . . . . . . . . . . . How Working with Variable-Size Data Is Different for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bounded Versus Unbounded Variable-Size Data . . . . . . When to Use Dynamic Allocation for Variable-Size Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How to Generate Code for MATLAB Functions with Variable-Size Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tutorial: Generating MEX Code for a MATLAB Function That Expands a Vector in a Loop . . . . . . . . About the MATLAB Function emldemo_uniquetol . . . . . . . Step 1: Add Compilation Directive for Code Generation . . Step 2: Address Issues Detected by the Code Analyzer . . . Step 3: Generate MEX Code . . . . . . . . . . . . . . . . . . . . . . . . . Step 4: Fix the Size Mismatch Error . . . . . . . . . . . . . . . . . . Step 5: Fix the Upper Bounds Error . . . . . . . . . . . . . . . . . . Step 6: Generate C/C++ Code . . . . . . . . . . . . . . . . . . . . . . . . Variable-Size Data in Code Generation Reports . . . . . . What Reports Tell You About Size . . . . . . . . . . . . . . . . . . . . How Size Appears in Code Generation Reports . . . . . . . . . How to Generate a Code Generation Report . . . . . . . . . . . . Defining Variable-Size Data for Code Generation . . . . . 8-2 8-3 8-3 8-4

8-5 8-5

8-6

8-9 8-9 8-10 8-10 8-10 8-12 8-14 8-16 8-18 8-18 8-19 8-19 8-20

xi

When to Define Variable-Size Data Explicitly . . . . . . . . . . Using a Matrix Constructor with Nonconstant Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inferring Variable Size from Multiple Assignments . . . . . . Defining Variable-Size Data Explicitly Using coder.varsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying Upper Bounds for Variable-Size Data . . . . . When to Specify Upper Bounds for Variable-Size Data . . . Specifying Upper Bounds on the Command Line for Variable-Size Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying Unknown Upper Bounds for Variable-Size Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying Upper Bounds for Local Variable-Size Data . . . C Code Interface for Unbounded Arrays and Structure Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . emxArray: Representation of Data with Unknown Upper Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Utility Functions for Creating emxArray Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Troubleshooting Issues with Variable-Size Data . . . . . . Diagnosing and Fixing Size Mismatch Errors . . . . . . . . . . . Diagnosing and Fixing Errors in Detecting Upper Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limitations with Variable-Size Support for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limitation on Scalar Expansion . . . . . . . . . . . . . . . . . . . . . . Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays . . . . . . . . . . . . . . . . . . . . . . . . . Limitation on Vector-Vector Indexing . . . . . . . . . . . . . . . . . Limitations on Matrix Indexing Operations for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dynamic Memory Allocation Not Supported for MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limitation on Mixing Stack and Heap Allocation . . . . . . . . Restrictions on Variable Sizing in Toolbox Functions Supported for Code Generation . . . . . . . . . . . . . . . . . . . Common Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-20 8-21 8-21 8-23 8-27 8-27 8-27 8-27 8-28

8-30 8-30 8-31 8-33 8-33 8-35

8-37 8-37 8-38 8-39 8-40 8-41 8-41

8-42 8-42

xii

Contents

Toolbox Functions with Variable Sizing Restrictions . . . . .

8-43

Code Generation for Function Handles

9
How Working with Function Handles is Different for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Example: Defining and Passing Function Handles for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limitations with Function Handles for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2

9-3

9-6

Defining Functions for Code Generation

10
Specifying Variable Numbers of Arguments . . . . . . . . . . Supported Index Expressions . . . . . . . . . . . . . . . . . . . . . . . Using varargin and varargout in for-Loops . . . . . . . . . . When to Force Loop Unrolling . . . . . . . . . . . . . . . . . . . . . . . Example: Using Variable Numbers of Arguments in a for-Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Implementing Wrapper Functions with varargin and varargout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Example: Passing Variable Numbers of Arguments from One Function to Another . . . . . . . . . . . . . . . . . . . . . . . . . Passing Property/Value Pairs with varargin . . . . . . . . . 10-2 10-3 10-4 10-4 10-5

10-7 10-7 10-8

xiii

Rules for Using Variable Length Argument Lists for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10

Calling Functions for Code Generation

11
How MATLAB Resolves Function Calls in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Key Points About Resolving Function Calls . . . . . . . . . . . . Compile Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . . When to Use the Code Generation Path . . . . . . . . . . . . . . . 11-2 11-4 11-4 11-5

How MATLAB Resolves File Types on the Path for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-6 Adding the Compilation Directive %#codegen . . . . . . . . Calling Subfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-8 11-9

Calling Supported Toolbox Functions . . . . . . . . . . . . . . . 11-10 Calling MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . Declaring MATLAB Functions as Extrinsic Functions . . . Calling MATLAB Functions Using feval . . . . . . . . . . . . . . . How MATLAB Resolves Extrinsic Functions During Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Working with mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . Restrictions on Extrinsic Functions for Code Generation . . Limit on Function Arguments . . . . . . . . . . . . . . . . . . . . . . . 11-11 11-11 11-15 11-15 11-16 11-17 11-18

Generating Efficient and Reusable Code

12
Generating Efficient Code . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2

xiv

Contents

Unrolling for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inlining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Eliminating Redundant Copies of Function Inputs . . . . . . Generating Reusable Code . . . . . . . . . . . . . . . . . . . . . . . . .

12-2 12-2 12-2 12-4

Examples

A
Data Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation for Structures . . . . . . . . . . . . . . . . . . . . . Code Generation for Enumerated Data . . . . . . . . . . . . . . Code Generation for Variable-Size Data . . . . . . . . . . . . . Code Generation for Function Handles . . . . . . . . . . . . . . Using Variable-Length Argument Lists . . . . . . . . . . . . . . Optimizing Generated Code . . . . . . . . . . . . . . . . . . . . . . . . A-2 A-2 A-2 A-2 A-3 A-3 A-3

Index

xv

xvi

Contents

1
About Code Generation from MATLAB Algorithms
? “Direct Translation of MATLAB Algorithms to C/C++ Code” on page 1-2 ? “Prerequisites for Code Generation from MATLAB” on page 1-3 ? “Preparing MATLAB Code for C/C++ and MEX Code Generation” on page 1-4 ? “Expected Differences in Behavior After Compiling Your MATLAB Code” on page 1-5 ? “MATLAB Language Features Supported for Code Generation” on page 1-9 ? “MATLAB Language Features Not Supported for Code Generation” on page 1-11 ? “Related Products That Support Code Generation from MATLAB” on page 1-12

1

About Code Generation from MATLAB? Algorithms

Direct Translation of MATLAB Algorithms to C/C++ Code
You can automatically generate MEX functions and standalone C/C++ code from MATLAB? algorithms. With this capability, you can design, implement, and test software in the MATLAB environment, then automatically translate the algorithms to readable, efficient, and compact C/C++ code for deployment to desktop and embedded systems. The generated code contains optimizations tailored to meet the requirements of desktop and embedded applications for speed, memory use, and data type management. To verify the generated code in the MATLAB environment, you can generate MEX functions to compare with your original algorithm to determine whether they are functionally equivalent. In certain applications, you can also generate MEX functions to accelerate MATLAB algorithms.

1-2

Prerequisites for Code Generation from MATLAB?

Prerequisites for Code Generation from MATLAB
To generate C/C++ or MEX code from MATLAB algorithms, you must install the following software: ? MATLAB? Coder? product ? C/C++ compiler For more information, see: ? “Why Test MEX Functions in MATLAB?” in the MATLAB Coder documentation. ? “Generating C/C++ Code from MATLAB Code” in the MATLAB Coder documentation. ? “Accelerating MATLAB Algorithms” in the MATLAB Coder documentation.

1-3

1

About Code Generation from MATLAB? Algorithms

Preparing MATLAB Code for C/C++ and MEX Code Generation
By default, the MATLAB language uses dynamic typing. Properties of dynamically typed variables can change at runtime, allowing a single variable to hold a value of any class, size, or complexity. However, to generate efficient code for statically typed languages such as C and C++, the properties of all MATLAB variables must be determined at compile time. Therefore, to prepare MATLAB code for C, C++, and MEX code generation, you must specify the class, size, and complexity of inputs to the primary function (also known as the top-level or entry-point function). By determining these properties at compile time, the code generation process translates your MATLAB algorithms into code that is efficient and tailored to your specific application, rather than producing generic code that handles every possible set of MATLAB inputs.

1-4

Expected Differences in Behavior After Compiling Your MATLAB? Code

Expected Differences in Behavior After Compiling Your MATLAB Code
In this section... “Why Are There Differences?” on page 1-5 “Character Size” on page 1-5 “Order of Evaluation in Expressions” on page 1-5 “Termination Behavior” on page 1-6 “Size of Variable-Size N-D Arrays” on page 1-6 “Floating-Point Numerical Results” on page 1-7 “NaN and Infinity Patterns” on page 1-7 “Code Generation Target” on page 1-7

Why Are There Differences?
To convert MATLAB code to C/C++ code that works efficiently, the code generation process introduces optimizations that intentionally cause the generated code to behave differently — and sometimes produce different results — from the original source code. This section describes these differences.

Character Size
MATLAB supports 16-bit characters, but the generated code represents characters in 8 bits, the standard size for most embedded languages like C. See “Code Generation for Characters” on page 5-6.

Order of Evaluation in Expressions
Generated code does not enforce order of evaluation in expressions. For most expressions, order of evaluation is not significant. However, for expressions with side effects, the generated code may produce the side effects in different order from the original MATLAB code. Expressions that produce side effects include those that:

1-5

1

About Code Generation from MATLAB? Algorithms

? Modify persistent or global variables ? Display data to the screen ? Write data to files In addition, the generated code does not enforce order of evaluation of logical operators that do not short circuit. For more predictable results, it is good coding practice to split expressions that depend on the order of evaluation into multiple statements. For example, rewrite:
A = f1() + f2();

as
A = f1(); A = A + f2();

so that the generated code calls f1 before f2.

Termination Behavior
Generated code does not match the termination behavior of MATLAB source code. For example, optimizations remove infinite loops from generated code if they have no side effects. As a result, the generated code may terminate even though the corresponding MATLAB code does not.

Size of Variable-Size N-D Arrays
For variable-size N-D arrays, the size function might return a different result in generated code than in MATLAB source code. The size function sometimes returns trailing ones (singleton dimensions) in generated code, but always drops trailing ones in MATLAB. For example, for an N-D array X with dimensions [4 2 1 1], size(X) might return [4 2 1 1] in generated code, but always returns [4 2] in MATLAB. See “Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays” on page 8-38.

1-6

Expected Differences in Behavior After Compiling Your MATLAB? Code

Floating-Point Numerical Results
The generated code might not produce the same floating-point numerical results as MATLAB in the following situations: When computer hardware uses extended precision registers Results vary depending on how the C/C++ compiler allocates extended precision floating-point registers. Computation results might not match MATLAB calculations because of different compiler optimization settings or different code surrounding the floating-point calculations. For certain advanced library functions The generated code might use different algorithms to implement certain advanced library functions, such as fft, svd, eig, mldivide, and mrdivide. For example, the generated code uses a simpler algorithm to implement svd to accommodate a smaller footprint. Results might also vary according to matrix properties. For example, MATLAB might detect symmetric or Hermitian matrices at run time and switch to specialized algorithms that perform computations faster than implementations in the generated code. For implementation of BLAS library functions For implementations of BLAS library functions. Generated C/C++ code uses reference implementations of BLAS functions, which may produce different results from platform-specific BLAS implementations in MATLAB.

NaN and Infinity Patterns
The generated code might not produce exactly the same pattern of NaN and inf values as MATLAB code when these values are mathematically meaningless. For example, if MATLAB output contains a NaN, output from the generated code should also contain a NaN, but not necessarily in the same place.

Code Generation Target
The coder.target function returns different values in MATLAB than in the generated code. The intent is to help you determine whether your function

1-7

1

About Code Generation from MATLAB? Algorithms

is executing in MATLAB or has been compiled for a simulation or code generation target. See coder.target.

1-8

MATLAB? Language Features Supported for Code Generation

MATLAB Language Features Supported for Code Generation
MATLAB supports the following language features in generated code: ? N-dimensional arrays ? Matrix operations, including deletion of rows and columns ? Variable-sized data (see “How Working with Variable-Size Data Is Different for Code Generation” on page 8-3) ? Subscripting (see “Limitations on Matrix Indexing Operations for Code Generation” on page 8-40) ? Complex numbers (see “Code Generation for Complex Data” on page 5-4) ? Numeric classes (see “Supported Variable Types” on page 4-16) ? Double-precision, single-precision, and integer math ? Fixed-point arithmetic (see “Code Acceleration and Code Generation from MATLAB for Fixed-Point Algorithms” in the Fixed-Point Toolbox? documentation) ? Program control statements if, switch, for, and while ? All arithmetic, relational, and logical operators ? Subfunctions (see Chapter 11, “Calling Functions for Code Generation”) ? Persistent variables (see “Defining and Initializing Persistent Variables” on page 4-10) ? Global variables (see “Specifying Global Variable Type and Initial Value in a Project” in the MATLAB Coder documentation. ? Structures (see Chapter 6, “Code Generation for MATLAB Structures”) ? Characters (see “Code Generation for Characters” on page 5-6) ? Function handles (see Chapter 9, “Code Generation for Function Handles”) ? Frames (see “Working with Frame-Based Signals” in the Simulink? documentation. ? Variable length input and output argument lists (see Chapter 8, “Code Generation for Variable-Size Data”)

1-9

1

About Code Generation from MATLAB? Algorithms

? Subset of MATLAB toolbox functions (see Chapter 2, “Functions Supported for Code Generation”) ? Ability to call functions (see “How MATLAB Resolves Function Calls in Generated Code” on page 11-2)

1-10

MATLAB? Language Features Not Supported for Code Generation

MATLAB Language Features Not Supported for Code Generation
MATLAB does not support the following features in generated code: ? Anonymous functions ? Cell arrays ? Java? ? Nested functions ? Objects ? Recursion ? Sparse matrices ? try/catch statements

1-11

1

About Code Generation from MATLAB? Algorithms

Related Products That Support Code Generation from MATLAB
You can also generate code from MATLAB using other MathWorks? products that require additional licenses: To: Generate C/C++ code from MATLAB in a Simulink model Do This: Add MATLAB Function blocks and MATLAB Truth Table blocks to the model. Required Licenses ? Simulink ? MATLAB Coder ? Simulink? Coder? and/or Embedded Coder? Details See: ? “Using the MATLAB Function Block” in the Simulink documentation ? “Building a Model with a Stateflow Truth Table” in the Stateflow? documentation See “Using MATLAB Functions in Stateflow Charts” and “Truth Table Functions for Decision-Making Logic” in the Stateflow documentation.

Generate C/C++ code from a Stateflow chart

Add MATLAB functions and MATLAB Truth Table functions to the chart.

? Stateflow ? Simulink ? MATLAB Coder ? Simulink Coder

1-12

Related Products That Support Code Generation from MATLAB?

To: Accelerate fixed-point algorithms in your MATLAB code

Do This: Compile the MATLAB code with the fiaccel function.

Required Licenses Fixed-Point Toolbox

Details See “Code Acceleration and Code Generation from MATLAB for Fixed-Point Algorithms” in the Fixed-Point Toolbox documentation. See “Working with Entities” in the SimEvents documentation.

Write and simulate MATLAB functions that manipulate data associated with entities Verify that the simulation behavior of a model satisfies test objectives Use MATLAB functions for proving properties and generating tests

? SimEvents? ? Simulink ? MATLAB Coder ? Simulink Coder ? Simulink? Design Verifier? ? Simulink ? MATLAB Coder ? Simulink Coder

See “About Property Proving” and “About Test Case Generation” in the Simulink Design Verifier documentation

1-13

1

About Code Generation from MATLAB? Algorithms

1-14

2
Functions Supported for Code Generation
? “About Code Generation for Supported Functions” on page 2-2 ? “Functions Supported for Code Generation — Alphabetical List” on page 2-3 ? “Functions Supported for Code Generation — Categorical List” on page 2-59

2

Functions Supported for Code Generation

About Code Generation for Supported Functions
You can generate efficient C/C++ code for a subset of MATLAB and toolbox functions that you call from MATLAB code. In generated code, each supported function has the same name, arguments, and functionality as its MATLAB or toolbox counterparts. However, to generate code for these functions, you must adhere to certain limitations when calling them from your MATLAB source code. These limitations appear in “Functions Supported for Code Generation — Alphabetical List” on page 2-3. To see at a glance whether there is support for a function in a particular MATLAB category or toolbox, see “Functions Supported for Code Generation — Categorical List” on page 2-59. Note For more information on code generation for fixed-point algorithms, refer to “Code Acceleration and Code Generation from MATLAB for Fixed-Point Algorithms” in the Fixed-Point Toolbox documentation.

2-2

Functions Supported for Code Generation — Alphabetical List

Functions Supported for Code Generation — Alphabetical List
Function
abs abs acos

Product MATLAB Fixed-Point Toolbox MATLAB

Remarks/Limitations — — ? Generates an error during simulation and returns NaN in generated code when the input value x is real, but the output should be complex. To get the complex result, make the input value complex by passing in complex(x). — ? Generates an error during simulation and returns NaN in generated code when the input value x is real, but the output should be complex. To get the complex result, make the input value complex by passing in complex(x). — — — — — — — — — —

acosd acosh

MATLAB MATLAB

acot acotd acoth acsc acscd acsch add all all and

MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB

2-3

2

Functions Supported for Code Generation

Function
angle any any asec asecd asech asin

Product MATLAB MATLAB Fixed-Point Toolbox MATLAB MATLAB MATLAB MATLAB

Remarks/Limitations — — — — — — ? Generates an error during simulation and returns NaN in generated code when the input value x is real, but the output should be complex. To get the complex result, make the input value complex by passing in complex(x). — — ? Generates specified error messages at compile time only if all input arguments are constants or depend on constants. Otherwise, generates specified error messages at run time. — — — ? Generates an error during simulation and returns NaN in generated code when the input value x is real, but the output should be complex. To get the complex result, make the input value complex by passing in complex(x).

asind asinh assert

MATLAB MATLAB MATLAB

atan atan2 atand atanh

MATLAB MATLAB MATLAB MATLAB

2-4

Functions Supported for Code Generation — Alphabetical List

Function
barthannwin

Product Signal Processing Toolbox?

Remarks/Limitations ? Window length must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox? license to generate code.

bartlett

Signal Processing Toolbox

? Window length must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

besselap

Signal Processing Toolbox

? Filter order must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

2-5

2

Functions Supported for Code Generation

Function
beta betainc betaln bi2de bin2dec bitand bitand bitandreduce bitcmp

Product MATLAB MATLAB MATLAB Communications System Toolbox? MATLAB MATLAB Fixed-Point Toolbox Fixed-Point Toolbox MATLAB

Remarks/Limitations — — — ? Requires a Communications System Toolbox license to generate code. — ? Does not support floating-point inputs. The arguments must belong to an integer class. ? Not supported for slope-bias scaled fi objects. — ? Does not support floating-point input for the first argument. The first argument must belong to an integer class. —

bitcmp

Fixed-Point Toolbox

bitconcat bitget bitget bitmax bitor bitor bitorreduce

Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB MATLAB Fixed-Point Toolbox Fixed-Point Toolbox

— — — — ? Does not support floating-point inputs. The arguments must belong to an integer class. ? Not supported for slope-bias scaled fi objects. —

2-6

Functions Supported for Code Generation — Alphabetical List

Function
bitreplicate bitrevorder

Product Fixed-Point Toolbox Signal Processing Toolbox Fixed-Point Toolbox Fixed-Point Toolbox MATLAB

Remarks/Limitations — ? Computation performed at run time. ? Requires DSP System Toolbox license to generate code. — — ? Does not support floating-point input for the first argument. The first argument must belong to an integer class. — ? Does not support floating-point input for the first argument. The first argument must belong to an integer class. — — — — — ? Does not support floating-point inputs. The arguments must belong to an integer class. ? Not supported for slope-bias scaled fi objects.

bitrol bitror bitset

bitset bitshift

Fixed-Point Toolbox MATLAB

bitshift bitsliceget bitsll bitsra bitsrl bitxor bitxor

Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox MATLAB Fixed-Point Toolbox

2-7

2

Functions Supported for Code Generation

Function
bitxorreduce blackman

Product Fixed-Point Toolbox Signal Processing Toolbox

Remarks/Limitations — ? Window length must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

blackmanharris

Signal Processing Toolbox

? Window length must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

blanks

MATLAB



2-8

Functions Supported for Code Generation — Alphabetical List

Function
bohmanwin

Product Signal Processing Toolbox

Remarks/Limitations ? Window length must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

bsxfun buttap

MATLAB Signal Processing Toolbox

— ? Filter order must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

butter

Signal Processing Toolbox

? Filter coefficients must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”.

2-9

2

Functions Supported for Code Generation

Function

Product

Remarks/Limitations ? Requires DSP System Toolbox license to generate code.

buttord

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

cart2pol cart2sph cast cat ceil ceil cfirpm

MATLAB MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox Signal Processing Toolbox

— — — — — — ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

2-10

Functions Supported for Code Generation — Alphabetical List

Function
char cheb1ap

Product MATLAB Signal Processing Toolbox

Remarks/Limitations — ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

cheb1ord

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

cheb2ap

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”.

2-11

2

Functions Supported for Code Generation

Function

Product

Remarks/Limitations ? Requires DSP System Toolbox license to generate code.

cheb2ord

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

chebwin

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

2-12

Functions Supported for Code Generation — Alphabetical List

Function
cheby1

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

cheby2

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

chol circshift class compan complex complex cond conj

MATLAB MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB MATLAB

— — — — — — — —

2-13

2

Functions Supported for Code Generation

Function
conj conv conv

Product Fixed-Point Toolbox MATLAB Fixed-Point Toolbox

Remarks/Limitations — — ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. ? For variable-sized signals, you may see different results between MATLAB and the generated code.

-

In generated code, the output for variable-sized signals is always computed using the SumMode property of the governing fimath. In MATLAB, the output for variable-sized signals is computed using the SumMode property of the governing fimath when both inputs are nonscalar. However, if either input is a scalar, MATLAB computes the output using the ProductMode of the governing fimath.

-

conv2 convergent convn cordicabs cordicangle cordicatan2

MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox

— — — ? Variable-size signals are not supported. ? Variable-size signals are not supported. ? Variable-size signals are not supported.

2-14

Functions Supported for Code Generation — Alphabetical List

Function
cordiccart2pol cordiccexp cordiccos cordicpol2cart cordicrotate cordicsin cordicsincos corrcoef cos cosd cosh cot cotd coth cov cross csc cscd csch ctranspose

Product Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB

Remarks/Limitations ? Variable-size signals are not supported. ? Variable-size signals are not supported. ? Variable-size signals are not supported. ? Variable-size signals are not supported. ? Variable-size signals are not supported. ? Variable-size signals are not supported. ? Variable-size signals are not supported. ? Row-vector input is only supported when the first two inputs are vectors and nonscalar. — — — — — — — ? If supplied, dim must be a constant. — — — —

2-15

2

Functions Supported for Code Generation

Function
ctranspose cumprod cumsum cumtrapz dct

Product Fixed-Point Toolbox MATLAB MATLAB MATLAB Signal Processing Toolbox

Remarks/Limitations — ? Logical inputs are not supported. Cast input to double first. ? Logical inputs are not supported. Cast input to double first. — ? Requires DSP System Toolbox license to generate code. ? Length of transform dimension must be a power of two. If specified, the pad or truncation value must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”.

de2bi deal deconv del2 det

Communications System Toolbox MATLAB MATLAB MATLAB

? Requires a Communications System Toolbox license to generate code. — — — —

2-16

Functions Supported for Code Generation — Alphabetical List

Function
detrend

Product MATLAB

Remarks/Limitations ? If supplied and not empty, the input argument bp must satisfy the following requirements:

-

Be real Be sorted in ascending order Restrict elements to integers in the interval [1, n-2], where n is the number of elements in a column of input argument X , or the number of elements in X when X is a row vector Contain all unique values

diag

MATLAB

? If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. ? If supplied, the index, k, must be a real and scalar integer value that is not a fi object. ? If supplied, the arguments representing the number of times to apply diff and the dimension along which to calculate the difference must be constants. — ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. ? Complex and imaginary divisors are not supported. ? The syntax T.divide(a,b) is not supported.

diag diff

Fixed-Point Toolbox MATLAB

disp divide

Fixed-Point Toolbox Fixed-Point Toolbox

dot double double

MATLAB MATLAB Fixed-Point Toolbox

— — —

2-17

2

Functions Supported for Code Generation

Function
downsample dpss

Product Signal Processing Toolbox Signal Processing Toolbox

Remarks/Limitations — ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

eig

MATLAB

? QZ algorithm used in all cases, whereas MATLAB might use different algorithms for different inputs. Consequently, V might represent a different basis of eigenvectors, and the eigenvalues in D might not be in the same order as in MATLAB. ? With one input, [V,D] = eig(A), the results will be similar to those obtained using [V,D] = eig(A,eye(size(A)),'qz') in MATLAB, except that for code generation, the columns of V are normalized. ? Options 'balance', 'nobalance' are not supported for the standard eigenvalue problem, and 'chol' is not supported for the symmetric generalized eigenvalue problem. ? Outputs are always of complex type.

2-18

Functions Supported for Code Generation — Alphabetical List

Function
ellip

Product Signal Processing Toolbox

Remarks/Limitations ? Inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

ellipap

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

ellipke ellipord

MATLAB Signal Processing Toolbox

— ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”.

2-19

2

Functions Supported for Code Generation

Function

Product

Remarks/Limitations ? Requires DSP System Toolbox license to generate code.

end eps eps

Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB Computer Vision System Toolbox? MATLAB MATLAB MATLAB MATLAB MATLAB

— — ? Supported for scalar fixed-point signals only. ? Supported for scalar, vector, and matrix, fi single and fi double signals. — ? Not supported for fixed-point signals with different biases. — — — — — ? This is an extrinsic call. —

eq eq erf erfc erfcinv erfcx erfinv error estimate Fundamental Matrix exp expint expm expm1 eye

— — — — ? Dimensions must be real, nonnegative, integer constants.

2-20

Functions Supported for Code Generation — Alphabetical List

Function
factor

Product MATLAB

Remarks/Limitations ? For double precision input, the maximum value of A is 2^32-1. ? For single precision input, the maximum value of A is 2^24-1.

factorial false fft fft2 fftn fftshift fi

MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox

— ? Dimensions must be real, nonnegative, integer constants. ? Length of input vector must be a power of 2. ? Length of input matrix dimensions must each be a power of 2. ? Length of input matrix dimensions must each be a power of 2. — ? Use to create a fixed-point constant or variable. ? The default constructor syntax without any input arguments is not supported. ? The syntax
fi('PropertyName',PropertyValue...)

is not supported. To use property name/property value pairs, you must first specify the value v of the fi object as in
fi(v,'PropertyName',PropertyValue...).

? Works for all input values when complete numerictype information of the fi object is provided. ? Works only for constant input values (value of input must be known at compile time) when complete numerictype information of the fi object is not specified. ? numerictype object information must be available for non-fixed-point Simulink inputs.

2-21

2

Functions Supported for Code Generation

Function
filter filter

Product MATLAB Fixed-Point Toolbox

Remarks/Limitations — ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. — ? Filter coefficients must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

filter2 filtfilt

MATLAB Signal Processing Toolbox

fimath

Fixed-Point Toolbox

? Fixed-point signals coming in to a MATLAB Function block from Simulink are assigned the fimath object defined in the MATLAB Function dialog in the Model Explorer. ? Use to create fimath objects in generated code.

2-22

Functions Supported for Code Generation — Alphabetical List

Function
find

Product MATLAB

Remarks/Limitations ? Issues an error if a variable-sized input becomes a row vector at run time. Note This limitation does not apply when the input is scalar or a variable-length row vector. ? For variable-sized inputs, the shape of empty outputs, 0-by-0, 0-by-1, or 1-by-0, depends on the upper bounds of the size of the input. The output might not match MATLAB when the input array is a scalar or [] at run time. If the input is a variable-length row vector, the size of an empty output is 1-by-0, otherwise it is 0-by-1.

fir1

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

2-23

2

Functions Supported for Code Generation

Function
fir2

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

fircls

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

fircls1

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

2-24

Functions Supported for Code Generation — Alphabetical List

Function
firls

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

firpm

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

firpmord

Signal Processing Toolbox

? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

2-25

2

Functions Supported for Code Generation

Function
firrcos

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

fix fix flattopwin

MATLAB Fixed-Point Toolbox Signal Processing Toolbox

— — ? All inputs must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

flipdim fliplr flipud floor floor freqspace

MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB

— — — — — —

2-26

Functions Supported for Code Generation — Alphabetical List

Function
freqz

Product Signal Processing Toolbox

Remarks/Limitations ? freqz with no output arguments produces a plot only when the function call terminates in a semicolon. See “freqz With No Output Arguments”. ? Requires DSP System Toolbox license to generate code.

fspecial

Image Processing Toolbox? MATLAB MATLAB

All inputs must be constants at compilation time. Expressions or variables are allowed if their values do not change. — ? The first argument must be a function handle. Does not support structure, inline function, or string inputs for the first argument. ? Supports up to three output arguments. Does not support the fourth output argument (the output structure). ? Only supports the TolX and FunValCheck fields of an options input structure. Ignores all other options in an options input structure. You cannot use the optimset function to create the options structure. Create this structure directly, for example,
opt.TolX = tol; opt.FunValCheck = 'on';

full fzero

The input structure field names must match exactly.
gamma gammainc gammaln

MATLAB MATLAB MATLAB

— — —

2-27

2

Functions Supported for Code Generation

Function
gaussfir

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

gausswin

Signal Processing Toolbox

? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

gcd ge ge get getlsb

MATLAB MATLAB Fixed-Point Toolbox Fixed-Point Toolbox Fixed-Point Toolbox

— — ? Not supported for fixed-point signals with different biases. ? The syntax structure = get(o) is not supported. —

2-28

Functions Supported for Code Generation — Alphabetical List

Function
getmsb

Product Fixed-Point Toolbox

Remarks/Limitations —

gradient gt gt hadamard hamming

MATLAB MATLAB Fixed-Point Toolbox MATLAB Signal Processing Toolbox

— — ? Not supported for fixed-point signals with different biases. — ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

hankel hann

MATLAB Signal Processing Toolbox

— ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

2-29

2

Functions Supported for Code Generation

Function
hex2dec hilb hist

Product MATLAB MATLAB MATLAB

Remarks/Limitations — — ? Histogram bar plotting not supported; call with at least one output argument. ? If supplied, the second argument x must be a scalar constant. ? Inputs must be real.

histc

MATLAB

? The output of a variable-size array that becomes a column vector at run time is a column-vector, not a row-vector. — — ? Length of transform dimension must be a power of two. If specified, the pad or truncation value must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

horzcat hypot idct

Fixed-Point Toolbox MATLAB Signal Processing Toolbox

idivide

MATLAB

? opt string must be in lowercase. ? For efficient generated code, MATLAB rules for divide by zero are supported only for the 'round' option.

2-30

Functions Supported for Code Generation — Alphabetical List

Function
ifft

Product MATLAB

Remarks/Limitations ? Length of input vector must be a power of 2. ? Output of ifft block is always complex. ? Does not support the 'symmetric' option.

ifft2

MATLAB

? Length of input matrix dimensions must each be a power of 2. ? Does not support the 'symmetric' option. ? Length of input matrix dimensions must each be a power of 2. ? Does not support the 'symmetric' option. — — — ? The first argument should be a valid size vector. Size vectors for arrays with more than intmax elements are not supported. ? Dimensions must be real, nonnegative, integer constants. — — ? Supports only linear and nearest interpolation methods. ? Does not handle evenly spaced X indices separately. ? X must be strictly monotonically increasing or strictly monotonically decreasing; does not reorder indices.

ifftn

MATLAB

ifftshift imag imag ind2sub

MATLAB MATLAB Fixed-Point Toolbox MATLAB

inf int8, int16, int32 int, int8, int16, int32 interp1

MATLAB MATLAB Fixed-Point Toolbox MATLAB

2-31

2

Functions Supported for Code Generation

Function
interp1q, see interp1

Product MATLAB

Remarks/Limitations ? X must be strictly monotonically increasing or strictly monotonically decreasing; does not reorder indices. ? When rows is not specified:

intersect

MATLAB

-

Inputs must be row vectors. If a vector is variable-sized, its first dimension must have a fixed length of 1. The input [] is not supported. Use a 1-by-0 input, for example zeros(1,0), to represent the empty set. Empty outputs are always row vectors, 1-by-0, never 0-by-0.

? When rows is specified, outputs ia and ib are always column vectors. If these outputs are empty, they are 0-by-1, never 0-by-0, even if the output c is 0-by-0. ? Inputs must already be sorted in ascending order. The first output is always sorted in ascending order. ? Complex inputs must be single or double.
intfilt

Signal Processing Toolbox

? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

intmax

MATLAB



2-32

Functions Supported for Code Generation — Alphabetical List

Function
intmin inv invhilb ipermute isa iscell ischar iscolumn iscolumn isdeployed

Product MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB? Compiler? MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox Fixed-Point Toolbox

Remarks/Limitations — Singular matrix inputs can produce nonfinite values that differ from MATLAB results. — — — — — — — ? Returns true and false as appropriate for MEX and SIM targets ? Returns false for all other targets — — — — — — ? Does not support cell input for second argument — —

isempty isempty isequal isequal isequalwithequalnans isfi isfield isfimath isfimathlocal

2-33

2

Functions Supported for Code Generation

Function
isfinite isfinite isfloat isinf isinf isinteger islogical ismatrix ismcc

Product MATLAB Fixed-Point Toolbox MATLAB MATLAB Fixed-Point Toolbox MATLAB MATLAB MATLAB MATLAB Compiler MATLAB

Remarks/Limitations — — — — — — — — ? Returns true and false as appropriate for MEX and SIM targets. ? Returns false for all other targets. ? The second input, S, must be sorted in ascending order. ? Complex inputs must be single or double. — — — — —

ismember

isnan isnan isnumeric isnumeric isnumerictype

MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox Fixed-Point Toolbox

2-34

Functions Supported for Code Generation — Alphabetical List

Function
isprime

Product MATLAB

Remarks/Limitations ? For double precision input, the maximum value of A is 2^32-1. ? For single precision input, the maximum value of A is 2^24-1.

isreal isreal isrow isrow isscalar isscalar issigned issorted issparse isstruct istrellis isvector

MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox Fixed-Point Toolbox MATLAB MATLAB MATLAB Communications System Toolbox MATLAB

— — — — — — — — — — ? Requires a Communications System Toolbox license to generate code. —

2-35

2

Functions Supported for Code Generation

Function
isvector kaiser

Product Fixed-Point Toolbox Signal Processing Toolbox

Remarks/Limitations — ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

kaiserord

Signal Processing Toolbox MATLAB Image Processing Toolbox

? Computation performed at run time. ? Requires DSP System Toolbox license to generate code. — Referring to the standard syntax:
RGB = label2rgb(L, map, zerocolor, order)

kron label2rgb

? Submit at least two input arguments: the label matrix, L, and the colormap matrix, map. ? map must be an n-by-3, double, colormap matrix. You cannot use a string containing the name of a MATLAB colormap function or a function handle of a colormap function. ? If you set the boundary color zerocolor to the same color as one of the regions, label2rgb will not issue a warning. ? If you supply a value for order, it must be 'noshuffle'.

2-36

Functions Supported for Code Generation — Alphabetical List

Function
lcm ldivide le le length length levinson

Product MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox Signal Processing Toolbox

Remarks/Limitations — — — ? Not supported for fixed-point signals with different biases. — — ? If specified, the order of recursion must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

linsolve

MATLAB

? The option structure must be a constant. ? Supports only a scalar option structure input. It does not support arrays of option structures. ? Only optimizes these cases:

-

UT LT UHESS = true (the TRANSA can be either true or false) SYM = true and POSDEF = true

All other options are equivalent to using mldivide.

2-37

2

Functions Supported for Code Generation

Function
linspace

Product MATLAB

Remarks/Limitations —

log

MATLAB

? Generates an error during simulation and returns NaN in generated code when the input value x is real, but the output should be complex. To get the complex result, make the input value complex by passing in complex(x). — — — — — — — ? Supported for scalar fixed-point signals only. ? Supported for scalar, vector, and matrix, fi single and double signals. — ? Not supported for fixed-point signals with different biases. — — —

log2 log10 log1p logical logical logspace lowerbound lsb

MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB MATLAB MATLAB

lt lt lu magic max

2-38

Functions Supported for Code Generation — Alphabetical List

Function
max maxflat

Product Fixed-Point Toolbox Signal Processing Toolbox

Remarks/Limitations — ? Inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

mean mean median median meshgrid min min minus minus

MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB MATLAB

— — — — — — — — ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. — ? Performs all arithmetic in the output class. Hence, results might not match MATLAB due to different rounding errors.

mldivide mod

2-39

2

Functions Supported for Code Generation

Function
mode mpower mpower

Product MATLAB MATLAB Fixed-Point Toolbox

Remarks/Limitations ? Does not support third output argument C (cell array) — ? The exponent input, k, must be constant; that is, its value must be known at compile time. ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. ? For variable-sized signals, you may see different results between MATLAB and the generated code.

-

In generated code, the output for variable-sized signals is always computed using the SumMode property of the governing fimath. In MATLAB, the output for variable-sized signals is computed using the SumMode property of the governing fimath when both inputs are nonscalar. However, if either input is a scalar, MATLAB computes the output using the ProductMode of the governing fimath.

-

mpy

Fixed-Point Toolbox

? When you provide complex inputs to the mpy function inside a MATLAB Function block, you must declare the input as complex before running the simulation. To do so, go to the Ports and data manager and set the Complexity parameter for all known complex inputs to On. — —

mrdivide mrdivide

MATLAB Fixed-Point Toolbox

2-40

Functions Supported for Code Generation — Alphabetical List

Function
mtimes mtimes

Product MATLAB Fixed-Point Toolbox

Remarks/Limitations — ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. ? For variable-sized signals, you may see different results between MATLAB and the generated code.

-

In generated code, the output for variable-sized signals is always computed using the SumMode property of the governing fimath. In MATLAB, the output for variable-sized signals is computed using the SumMode property of the governing fimath when both inputs are nonscalar. However, if either input is a scalar, MATLAB computes the output using the ProductMode of the governing fimath.

-

NaN or nan
nargchk nargin

MATLAB MATLAB MATLAB

? Dimensions must be real, nonnegative, integer constants ? Output structure does not include stack information. —

2-41

2

Functions Supported for Code Generation

Function
nargout

Product MATLAB

Remarks/Limitations ? For a function with no output arguments, returns 1 if called without a terminating semicolon. Note This behavior also affects extrinsic calls with no terminating semicolon. nargout is 1 for the called function in MATLAB.

nargoutchk nchoosek ndgrid ndims ndims ne ne nearest nextpow2 nnz nonzeros norm normest

MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox Fixed-Point Toolbox MATLAB MATLAB MATLAB MATLAB MATLAB

? Output structure does not include stack information. — — — — — ? Not supported for fixed-point signals with different biases. — — — — — —

not nthroot

MATLAB MATLAB

— —

2-42

Functions Supported for Code Generation — Alphabetical List

Function
null

Product MATLAB

Remarks/Limitations ? Might return a different basis than MATLAB ? Does not support rational basis option (second input)

numberofelements

Fixed-Point Toolbox MATLAB

? Returns the number of elements of fi objects in the generated code (works the same as numel for fi objects in generated code). ? Returns the number of elements of fi objects in the generated code, rather than always returning 1. ? Fixed-point signals coming in to a MATLAB Function block from Simulink are assigned a numerictype object that is populated with the signal’s data type and scaling information. ? Returns the data type when the input is a non-fixed-point signal. ? Use to create numerictype objects in the generated code.

numel

numerictype

Fixed-Point Toolbox

nuttallwin

Signal Processing Toolbox

? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

ones or orth

MATLAB MATLAB MATLAB

? Dimensions must be real, nonnegative, integer constants — ? Might return a different basis than MATLAB

2-43

2

Functions Supported for Code Generation

Function
parzenwin

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

pascal permute permute pi pinv planerot plus plus

MATLAB MATLAB Fixed-Point Toolbox MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB MATLAB

— — — — — — — ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. — ? Does not discard nonfinite input values ? Complex input always produces complex output

pol2cart poly

poly2trellis polyfit polyval

Communications System Toolbox MATLAB MATLAB

? Requires a Communications System Toolbox license to generate code. — —

2-44

Functions Supported for Code Generation — Alphabetical List

Function
pow2 power

Product Fixed-Point Toolbox MATLAB

Remarks/Limitations — ? Generates an error during simulation and returns NaN in generated code when both X and Y are real, but power(X,Y) is complex. To get the complex result, make the input value X complex by passing in complex(X). For example, power(complex(X),Y). ? Generates an error during simulation and returns NaN in generated code when both X and Y are real, but X .^ Y is complex. To get the complex result, make the input value X complex by using complex(X). For example, complex(X).^Y.

power primes prod qr quad2d

Fixed-Point Toolbox MATLAB MATLAB MATLAB MATLAB

? The exponent input, k, must be constant; that is, its value must be known at compile time. — — — ? Generates a warning if the size of the internal storage arrays is not sufficient. If a warning occurs, a possible workaround is to divide the region of integration into pieces and sum the integrals over each piece.

quadgk quatconj quatdivide quatinv

MATLAB Aerospace Toolbox Aerospace Toolbox Aerospace Toolbox

— — — —

2-45

2

Functions Supported for Code Generation

Function
quatmod quatmultiply quatnorm quatnormalize rand

Product Aerospace Toolbox Aerospace Toolbox Aerospace Toolbox Aerospace Toolbox MATLAB

Remarks/Limitations — — — — ? Supports only the mt19937ar (formerly known as ‘twister’) and mcg16807 (formerly known as ‘seed’) generators. ? When seeding the generator, you must terminate the call to rand with a semicolon in the generated code. ? May not match MATLAB results if seeded with negative values.

randn

MATLAB

? When seeding the generator, you must terminate the call to rand with a semicolon in the generated code. ? May not match MATLAB results if seeded with negative values

randperm range rank rcond

MATLAB Fixed-Point Toolbox MATLAB MATLAB

— — — —

rcosfir

Communications System Toolbox

? Requires a Communications System Toolbox license to generate code.

2-46

Functions Supported for Code Generation — Alphabetical List

Function
rdivide rdivide real real reallog realmax realmax realmin realmin realpow realsqrt rectwin

Product MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB MATLAB Signal Processing Toolbox

Remarks/Limitations — — — — — — — — — — — ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

reinterpretcast rem

Fixed-Point Toolbox MATLAB

— ? Performs all arithmetic in the output class. Hence, results might not match MATLAB due to different rounding errors.

2-47

2

Functions Supported for Code Generation

Function
repmat repmat resample

Product MATLAB Fixed-Point Toolbox Signal Processing Toolbox

Remarks/Limitations — — ? The upsampling and downsampling factors must be specified as constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

rescale reshape reshape roots

Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB

— — — ? Output is always variable size ? Output is always complex ? Roots may not be in the same order as MATLAB ? Roots of poorly conditioned polynomials may not match MATLAB

rosser rot90 round round

MATLAB MATLAB MATLAB Fixed-Point Toolbox

— — — —

2-48

Functions Supported for Code Generation — Alphabetical List

Function
rsf2csf schur

Product MATLAB MATLAB

Remarks/Limitations — Might sometimes return a different Schur decomposition in generated code than in MATLAB. —

sec

MATLAB

secd sech setdiff

MATLAB MATLAB MATLAB

— — ? When rows is not specified:

-

Inputs must be row vectors. If a vector is variable-sized, its first dimension must have a fixed length of 1. The input [] is not supported. Use a 1-by-0 input, for example, zeros(1,0) to represent the empty set. Empty outputs are always row vectors, 1-by-0, never 0-by-0.

? When rows is specified, output i is always a column vector. If i is empty, it is 0-by-1, never 0-by-0, even if the output c is 0-by-0. ? Inputs must already be sorted in ascending order. The first output is always sorted in ascending order. ? Complex inputs must be single or double.

2-49

2

Functions Supported for Code Generation

Function
setxor

Product MATLAB

Remarks/Limitations ? When rows is not specified:

-

Inputs must be row vectors. If a vector is variable-sized, its first dimension must have a fixed length of 1. The input [] is not supported. Use a 1-by-0 input, such as zeros(1,0), to represent the empty set. Empty outputs are always row vectors, 1-by-0, never 0-by-0.

? When rows is specified, outputs ia and ib are always column vectors. If these outputs are empty, they are 0-by-1, never 0-by-0, even if the output c is 0-by-0. ? Inputs must already be sorted in ascending order. The first output is always sorted in ascending order. ? Complex inputs must be single or double.
sfi sgolay

Fixed-Point Toolbox Signal Processing Toolbox

— ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

shiftdim

MATLAB

Second argument must be a constant.

2-50

Functions Supported for Code Generation — Alphabetical List

Function
sign sign sin sind single single sinh size size sort sort sortrows sosfilt

Product MATLAB Fixed-Point Toolbox MATLAB MATLAB MATLAB Fixed-Point Toolbox MATLAB MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB Signal Processing Toolbox

Remarks/Limitations — — — — — — — — — — — — ? Computation performed at run time. ? Requires DSP System Toolbox license to generate code.

sph2cart squeeze sqrt

MATLAB MATLAB MATLAB

— — ? Generates an error during simulation and returns NaN in generated code when the input value x is real, but the output should be complex. To get the complex result, make the input value complex by passing in complex(x). ? Complex and [Slope Bias] inputs error out. ? Negative inputs yield a 0 result.

sqrt

Fixed-Point Toolbox

2-51

2

Functions Supported for Code Generation

Function
sqrtm std str2func strcmp struct structfun

Product MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB

Remarks/Limitations — — ? String must be constant/known at compile time ? Arguments must be computable at compile time. — ? Does not support the ErrorHandler option. ? The number of outputs must be less than or equal to three.

sub sub2ind

Fixed-Point Toolbox MATLAB

— ? The first argument should be a valid size vector. Size vectors for arrays with more than intmax elements are not supported. — — — — ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. — Inheritance of the class of the input to swapbytes in a MATLAB Function block is supported only when the class of the input is double. For non-double inputs, the input port data types must be specified, not inherited.

subsasgn subspace subsref sum sum

Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox

svd swapbytes

MATLAB MATLAB

2-52

Functions Supported for Code Generation — Alphabetical List

Function
tan tand tanh taylorwin

Product MATLAB MATLAB MATLAB Signal Processing Toolbox MATLAB Fixed-Point Toolbox

Remarks/Limitations — — — ? Inputs must be constant ? Requires DSP System Toolbox license to generate code. — ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. ? When you provide complex inputs to the times function inside a MATLAB Function block, you must declare the input as complex before running the simulation. To do so, go to the Ports and data manager and set the Complexity parameter for all known complex inputs to On.

times times

toeplitz trace trapz transpose transpose

MATLAB MATLAB MATLAB MATLAB Fixed-Point Toolbox

— — — — —

2-53

2

Functions Supported for Code Generation

Function
triang

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

tril

MATLAB

? If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. ? If supplied, the index, k, must be a real and scalar integer value that is not a fi object. ? If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. ? If supplied, the index, k, must be a real and scalar integer value that is not a fi object. ? Dimensions must be real, nonnegative, integer constants

tril triu

Fixed-Point Toolbox MATLAB

triu true

Fixed-Point Toolbox MATLAB

2-54

Functions Supported for Code Generation — Alphabetical List

Function
tukeywin

Product Signal Processing Toolbox

Remarks/Limitations ? All inputs must be constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

typecast

MATLAB

? Value of string input argument type must be lower case ? You might receive a size error when you use typecast with inheritance of input port data types in MATLAB Function blocks. To avoid this error, specify the block’s input port data types explicitly.

ufi uint8, uint16, uint32 uint8, uint16, uint32 uminus uminus

Fixed-Point Toolbox MATLAB Fixed-Point Toolbox MATLAB Fixed-Point Toolbox

— — — — —

2-55

2

Functions Supported for Code Generation

Function
union

Product MATLAB

Remarks/Limitations ? When rows is not specified:

-

Inputs must be row vectors. If a vector is variable-sized, its first dimension must have a fixed length of 1. The input [] is not supported. Use a 1-by-0 input, such as zeros(1,0) to represent the empty set. Empty outputs are always row vectors, 1-by-0, never 0-by-0.

? When rows is specified, outputs ia and ib are always column vectors. If these outputs are empty, they are 0-by-1, never 0-by-0, even if the output c is 0-by-0. ? Inputs must already be sorted in ascending order. The first output is always sorted in ascending order. ? Complex inputs must be single or double.
unique

MATLAB

? When rows is not specified:

-

The first input must be a row vector. If the vector is variable-sized, its first dimension must have a fixed length of 1. The input [] is not supported. Use a 1-by-0 input, such as zeros(1,0), to represent the empty set. Empty outputs are always row vectors, 1-by-0, never 0-by-0.

? When rows is specified, outputs m and n are always column vectors. If these outputs are empty, they are 0-by-1, never 0-by-0, even if the output b is 0-by-0. ? Complex inputs must be single or double.

2-56

Functions Supported for Code Generation — Alphabetical List

Function
unwrap

Product MATLAB

Remarks/Limitations ? Row vector input is only supported when the first two inputs are vectors and nonscalar ? Performs all arithmetic in the output class. Hence, results might not match MATLAB due to different rounding errors

upfirdn

Signal Processing Toolbox

? Filter coefficients, upsampling factor, and downsampling factor must be constants. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Variable-size inputs are not supported. ? Requires DSP System Toolbox license to generate code

uplus uplus upperbound upsample

MATLAB Fixed-Point Toolbox Fixed-Point Toolbox Signal Processing Toolbox

— — — Either declare input n as constant, or use the assert function in the calling function to set upper bounds for n. For example,
assert(n<10)

vander var vertcat

MATLAB MATLAB Fixed-Point Toolbox

— — —

2-57

2

Functions Supported for Code Generation

Function
wilkinson xcorr

Product MATLAB Signal Processing Toolbox

Remarks/Limitations — ? Does not support the case where A is a matrix ? Does not support partial (abbreviated) strings of biased, unbiased, coeff, or none ? Computation performed at run time. ? Requires DSP System Toolbox license to generate code

xor yulewalk

MATLAB Signal Processing Toolbox

— ? If specified, the order of recursion must be a constant. Expressions or variables are allowed if their values do not change. Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specifying Constant Inputs at the Command Line”. ? Requires DSP System Toolbox license to generate code.

zeros zp2tf

MATLAB MATLAB

? Dimensions must be real, nonnegative, integer constants —

2-58

Functions Supported for Code Generation — Categorical List

Functions Supported for Code Generation — Categorical List
In this section... “Aerospace Toolbox Functions” on page 2-60 “Arithmetic Operator Functions” on page 2-60 “Bit-Wise Operation Functions” on page 2-61 “Casting Functions” on page 2-61 “Communications System Toolbox Functions” on page 2-62 “Complex Number Functions” on page 2-62 “Computer Vision System Toolbox Functions” on page 2-63 “Data Type Functions” on page 2-64 “Derivative and Integral Functions” on page 2-64 “Discrete Math Functions” on page 2-64 “Error Handling Functions” on page 2-65 “Exponential Functions” on page 2-65 “Filtering and Convolution Functions” on page 2-66 “Fixed-Point Toolbox Functions” on page 2-66 “Histogram Functions” on page 2-75 “Image Processing Toolbox Functions” on page 2-75 “Input and Output Functions” on page 2-76 “Interpolation and Computational Geometry” on page 2-76 “Linear Algebra” on page 2-77 “Logical Operator Functions” on page 2-77 “MATLAB Compiler Functions” on page 2-78 “Matrix and Array Functions” on page 2-78 “Nonlinear Numerical Methods” on page 2-82 “Polynomial Functions” on page 2-82

2-59

2

Functions Supported for Code Generation

In this section... “Relational Operator Functions” on page 2-82 “Rounding and Remainder Functions” on page 2-83 “Set Functions” on page 2-83 “Signal Processing Functions in MATLAB” on page 2-84 “Signal Processing Toolbox Functions” on page 2-84 “Special Values” on page 2-89 “Specialized Math” on page 2-89 “Statistical Functions” on page 2-90 “String Functions” on page 2-90 “Structure Functions” on page 2-91 “Trigonometric Functions” on page 2-91

Aerospace Toolbox Functions
Function
quatconj quatdivide quatinv quatmod quatmultiply quatnorm quatnormalize

Description Calculate conjugate of quaternion Divide quaternion by another quaternion Calculate inverse of quaternion Calculate modulus of quaternion Calculate product of two quaternions Calculate norm of quaternion Normalize quaternion

Arithmetic Operator Functions
See Arithmetic Operators + - * / \ ^ ’ in the MATLAB Function Reference documentation for detailed descriptions of the following operator equivalent functions.

2-60

Functions Supported for Code Generation — Categorical List

Function
ctranspose idivide isa ldivide minus mldivide mpower mrdivide mtimes plus power rdivide times transpose uminus uplus

Description Complex conjugate transpose (') Integer division with rounding option Determine if input is object of given class Left array divide Minus (-) Left matrix divide (\) Equivalent of array power operator (.^) Right matrix divide Matrix multiply (*) Plus (+) Array power Right array divide Array multiply Matrix transpose (') Unary minus (-) Unary plus (+)

Bit-Wise Operation Functions
Function
swapbytes

Description Swap byte ordering

Casting Functions
Data Type
cast char

Description Cast variable to different data type Create character array (string)

2-61

2

Functions Supported for Code Generation

Data Type
class double int8, int16, int32 logical single typecast uint8, uint16, uint32

Description Query class of object argument Convert to double-precision floating point Convert to signed integer data type Convert to Boolean true or false data type Convert to single-precision floating point Convert data types without changing underlying data Convert to unsigned integer data type

Communications System Toolbox Functions
Function
bi2de de2bi istrellis poly2trellis rcosfir

Remarks/Limitations — — — — —

Complex Number Functions
Function
complex conj imag isnumeric isreal isscalar

Description Construct complex data from real and imaginary components Return the conjugate of a complex number Return the imaginary part of a complex number Return true for numeric arrays Return false (0) for a complex number Return true if array is a scalar

2-62

Functions Supported for Code Generation — Categorical List

Function
real unwrap

Description Return the real part of a complex number Correct phase angles to produce smoother phase plots

Computer Vision System Toolbox Functions
Function
epipolarLine

Description Compute epipolar lines for stereo images

estimateFundamentalMatrix

Estimate fundamental matrix from corresponding points in stereo image

estimateUncalibratedRectification Uncalibrated stereo rectification

extractFeatures

Extract interest point descriptors

isEpipoleInImage

Determine whether image contains epipole

lineToBorderPoints

Intersection points of lines in image and image border

matchFeatures

Find matching image features

2-63

2

Functions Supported for Code Generation

Data Type Functions
Function
deal iscell nargchk nargoutchk str2func structfun

Description Distribute inputs to outputs Determine whether input is cell array Validate number of input arguments Validate number of output arguments Construct function handle from function name string Apply function to each field of scalar structure

Derivative and Integral Functions
Function
cumtrapz del2 diff gradient trapz

Description Cumulative trapezoidal numerical integration Discrete Laplacian Differences and approximate derivatives Numerical gradient Trapezoidal numerical integration

Discrete Math Functions
Function
factor gcd isprime lcm nchoosek primes

Description Return a row vector containing the prime factors of n Return an array containing the greatest common divisors of the corresponding elements of integer arrays Array elements that are prime numbers Least common multiple of corresponding elements in arrays Binomial coefficient or all combinations Generate list of prime numbers

2-64

Functions Supported for Code Generation — Categorical List

Error Handling Functions
Function
assert error

Description Generate error when condition is violated Display message and abort function

Exponential Functions
Function
exp expm expm1 factorial log log2 log10 log1p nextpow2 nthroot reallog realpow realsqrt sqrt

Description Exponential Matrix exponential Compute exp(x)-1 accurately for small values of x Factorial function Natural logarithm Base 2 logarithm and dissect floating-point numbers into exponent and mantissa Common (base 10) logarithm Compute log(1+x) accurately for small values of x Next higher power of 2 Real nth root of real numbers Natural logarithm for nonnegative real arrays Array power for real-only output Square root for nonnegative real arrays Square root

2-65

2

Functions Supported for Code Generation

Filtering and Convolution Functions
Function
conv conv2 convn deconv detrend filter filter2

Description Convolution and polynomial multiplication 2-D convolution N-D convolution Deconvolution and polynomial division Remove linear trends 1-D digital filter 2-D digital filter

Fixed-Point Toolbox Functions
In addition to any function-specific limitations listed in the table, the following general limitations always apply to the use of Fixed-Point Toolbox functions in generated code or with fiaccel: ? fipref and quantizer objects are not supported. ? Dot notation is only supported for getting the values of fimath and numerictype properties. Dot notation is not supported for fi objects, and it is not supported for setting properties. ? Word lengths greater than 128 bits are not supported. ? You cannot change the fimath or numerictype of a given variable after that variable has been created. ? The boolean and ScaledDouble values of the DataTypeMode and DataType properties are not supported. ? For all SumMode property settings other than FullPrecision, the CastBeforeSum property must be set to true. ? The numel function returns the number of elements of fi objects in the generated code. ? When you compile code containing fi objects with nontrivial slope and bias scaling, you may see different results in generated code than you achieve by running the same code in MATLAB.

2-66

Functions Supported for Code Generation — Categorical List

? All general limitations of C/C++ code generated from MATLAB apply. See “MATLAB Language Features Not Supported for Code Generation” on page 1-11 for more information. Function
abs add all any bitand bitandreduce bitcmp bitconcat bitget bitor bitorreduce bitreplicate bitrol bitror bitset bitshift bitsliceget bitsll bitsra bitsrl bitxor bitxorreduce ceil complex

Remarks/Limitations N/A N/A N/A N/A Not supported for slope-bias scaled fi objects. N/A N/A N/A N/A Not supported for slope-bias scaled fi objects. N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A Not supported for slope-bias scaled fi objects. N/A N/A N/A

2-67

2

Functions Supported for Code Generation

Function
conj conv

Remarks/Limitations N/A ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. ? For variable-sized signals, you may see different results between generated code and MATLAB.

-

In the generated code, the output for variable-sized signals is always computed using the SumMode property of the governing fimath. In MATLAB, the output for variable-sized signals is computed using the SumMode property of the governing fimath when both inputs are nonscalar. However, if either input is a scalar, MATLAB computes the output using the ProductMode of the governing fimath.

convergent cordicabs cordicangle cordicatan2 cordiccart2pol cordiccexp cordiccos cordicpol2cart cordicrotate cordicsin cordicsincos ctranspose diag disp

N/A Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. Variable-size signals are not supported. N/A If supplied, the index, k, must be a real and scalar integer value that is not a fi object. —

2-68

Functions Supported for Code Generation — Categorical List

Function
divide

Remarks/Limitations ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. ? Complex and imaginary divisors are not supported. ? Code generation in MATLAB does not support the syntax T.divide(a,b).

double end eps

N/A N/A ? Supported for scalar fixed-point signals only. ? Supported for scalar, vector, and matrix, fi single and fi double signals.

eq fi

Not supported for fixed-point signals with different biases. ? Use to create a fixed-point constant or variable in the generated code. ? The default constructor syntax without any input arguments is not supported. ? The syntax
fi('PropertyName',PropertyValue...)

is not supported. To use property name/property value pairs, you must first specify the value v of the fi object as in
fi(v,'PropertyName',PropertyValue...).

? Works for all input values when complete numerictype information of the fi object is provided. ? Works only for constant input values (value of input must be known at compile time) when complete numerictype information of the fi object is not specified.

2-69

2

Functions Supported for Code Generation

Function

Remarks/Limitations ? numerictype object information must be available for nonfixed-point Simulink inputs.

filter

? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. ? Fixed-point signals coming in to a MATLAB Function block from Simulink are assigned a fimath object. You define this object in the MATLAB Function block dialog in the Model Explorer. ? Use to create fimath objects in the generated code. N/A N/A Not supported for fixed-point signals with different biases. The syntax structure = get(o) is not supported. N/A N/A Not supported for fixed-point signals with different biases. N/A N/A N/A N/A N/A N/A N/A N/A

fimath

fix floor ge get getlsb getmsb gt horzcat imag

int, int8, int16, int32 N/A iscolumn isempty isequal isfi isfimath isfimathlocal

2-70

Functions Supported for Code Generation — Categorical List

Function
isfinite isinf isnan isnumeric isnumerictype isreal isrow isscalar issigned isvector le length logical lowerbound lsb

Remarks/Limitations N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A Not supported for fixed-point signals with different biases. N/A N/A N/A ? Supported for scalar fixed-point signals only. ? Supported for scalar, vector, and matrix, fi single and double signals.

lt max mean median min minus

Not supported for fixed-point signals with different biases. N/A N/A N/A N/A Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object.

2-71

2

Functions Supported for Code Generation

Function
mpower

Remarks/Limitations ? The exponent input, k, must be constant; that is, its value must be known at compile time. ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. ? For variable-sized signals, you may see different results between the generated code and MATLAB.

-

In the generated code, the output for variable-sized signals is always computed using the SumMode property of the governing fimath. In MATLAB, the output for variable-sized signals is computed using the SumMode property of the governing fimath when the first input, a, is nonscalar. However, when a is a scalar, MATLAB computes the output using the ProductMode of the governing fimath.

mpy

When you provide complex inputs to the mpy function inside of a MATLAB Function block, you must declare the input as complex before running the simulation. To do so, go to the Ports and data manager and set the Complexity parameter for all known complex inputs to On. N/A ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. ? Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. ? For variable-sized signals, you may see different results between the generated code and MATLAB.

mrdivide mtimes

2-72

Functions Supported for Code Generation — Categorical List

Function

Remarks/Limitations

-

In the generated code, the output for variable-sized signals is always computed using the SumMode property of the governing fimath. In MATLAB, the output for variable-sized signals is computed using the SumMode property of the governing fimath when both inputs are nonscalar. However, if either input is a scalar, MATLAB computes the output using the ProductMode of the governing fimath.

ndims ne nearest numberofelements numerictype

N/A Not supported for fixed-point signals with different biases. N/A
numberofelements and numel both work the same as MATLAB numel for fi objects in the generated code.

? Fixed-point signals coming in to a MATLAB Function block from Simulink are assigned a numerictype object that is populated with the signal’s data type and scaling information. ? Returns the data type when the input is a nonfixed-point signal. ? Use to create numerictype objects in generated code.

permute plus

N/A Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. N/A The exponent input, k, must be constant; that is, its value must be known at compile time. N/A

pow2 power range

2-73

2

Functions Supported for Code Generation

Function
rdivide real realmax realmin reinterpretcast repmat rescale reshape round sfi sign single size sort sqrt

Remarks/Limitations N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A ? Complex and [Slope Bias] inputs error out. ? Negative inputs yield a 0 result. N/A N/A N/A Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB.

sub subsasgn subsref sum

2-74

Functions Supported for Code Generation — Categorical List

Function
times

Remarks/Limitations ? Any non-fi input must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. ? When you provide complex inputs to the times function inside of a MATLAB Function block, you must declare the input as complex before running the simulation. To do so, go to the Ports and data manager and set the Complexity parameter for all known complex inputs to On.

transpose tril triu ufi

N/A If supplied, the index, k, must be a real and scalar integer value that is not a fi object. If supplied, the index, k, must be a real and scalar integer value that is not a fi object. N/A N/A N/A N/A N/A

uint8, uint16, uint32 N/A uminus uplus upperbound vertcat

Histogram Functions
Function
hist histc

Description Non-graphical histogram Histogram count

Image Processing Toolbox Functions
You must have the Image Processing Toolbox software installed to generate C/C++ code from MATLAB for these functions.

2-75

2

Functions Supported for Code Generation

Function
fspecial label2rgb

Remarks/Limitations All inputs must be constants at compilation time. Expressions or variables are allowed if their values do not change. Referring to the standard syntax:
RGB = label2rgb(L, map, zerocolor, order)

? Submit at least two input arguments: the label matrix, L, and the colormap matrix, map. ? map must be an n-by-3, double, colormap matrix. You cannot use a string containing the name of a MATLAB colormap function or a function handle of a colormap function. ? If you set the boundary color zerocolor to the same color as one of the regions, label2rgb will not issue a warning. ? If you supply a value for order, it must be 'noshuffle'.

Input and Output Functions
Function
nargin nargout

Description Return the number of input arguments a user has supplied Return the number of output return values a user has requested

Interpolation and Computational Geometry
Function
cart2pol cart2sph interp1 interp1q meshgrid

Description Transform Cartesian coordinates to polar or cylindrical Transform Cartesian coordinates to spherical One-dimensional interpolation (table lookup) Quick one-dimensional linear interpolation (table lookup) Generate X and Y arrays for 3-D plots

2-76

Functions Supported for Code Generation — Categorical List

Function
pol2cart sph2cart

Description Transform polar or cylindrical coordinates to Cartesian Transform spherical coordinates to Cartesian

Linear Algebra
Function
linsolve

Description Solve linear system of equations

null orth rsf2csf schur sqrtm

Null space Range space of matrix Convert real Schur form to complex Schur form Schur decomposition Matrix square root

Logical Operator Functions
Function
and bitand bitcmp bitget bitor bitset bitshift bitxor not

Description Logical AND (&&) Bitwise AND Bitwise complement Bit at specified position Bitwise OR Set bit at specified position Shift bits specified number of places Bitwise XOR Logical NOT (~)

2-77

2

Functions Supported for Code Generation

Function
or xor

Description Logical OR (||) Logical exclusive-OR

MATLAB Compiler Functions
Function
isdeployed ismcc

Description Determine whether code is running in deployed or MATLAB mode Test if code is running during compilation process (using mcc)

Matrix and Array Functions
Function
abs all angle any bsxfun cat circshift compan cond cov cross cumprod cumsum det

Description Return absolute value and complex magnitude of an array Test if all elements are nonzero Phase angle Test for any nonzero elements Applies element-by-element binary operation to two arrays with singleton expansion enabled Concatenate arrays along specified dimension Shift array circularly Companion matrix Condition number of a matrix with respect to inversion Covariance matrix Vector cross product Cumulative product of array elements Cumulative sum of array elements Matrix determinant

2-78

Functions Supported for Code Generation — Categorical List

Function
diag diff dot eig eye false find flipdim fliplr flipud full hadamard hankel hilb ind2sub inv invhilb ipermute iscolumn isempty isequal isequalwithequalnans isfinite isfloat isinf isinteger

Description Return a matrix formed around the specified diagonal vector and the specified diagonal (0, 1, 2,...) it occupies Differences and approximate derivatives Vector dot product Eigenvalues and eigenvectors Identity matrix Return an array of 0s for the specified dimensions Find indices and values of nonzero elements Flip array along specified dimension Flip matrix left to right Flip matrix up to down Convert sparse matrix to full matrix Hadamard matrix Hankel matrix Hilbert matrix Subscripts from linear index Inverse of a square matrix Inverse of Hilbert matrix Inverse permute dimensions of array True if input is a column vector Determine whether array is empty Test arrays for equality Test arrays for equality, treating NaNs as equal Detect finite elements of an array Determine if input is floating-point array Detect infinite elements of an array Determine if input is integer array

2-79

2

Functions Supported for Code Generation

Function
islogical ismatrix isnan isrow issparse isvector kron length linspace logspace lu magic max min ndgrid ndims nnz nonzeros norm normest numel ones pascal permute pinv planerot

Description Determine if input is logical array True if input is a matrix Detect NaN elements of an array True if input is a row vector Determine whether input is sparse Determine whether input is vector Kronecker tensor product Return the length of a matrix Generate linearly spaced vectors Generate logarithmically spaced vectors Matrix factorization Magic square Maximum elements of a matrix Minimum elements of a matrix Generate arrays for N-D functions and interpolation Number of dimensions Number of nonzero matrix elements Nonzero matrix elements Vector and matrix norms 2-norm estimate Number of elements in array or subscripted array Create a matrix of all 1s Pascal matrix Rearrange dimensions of array Pseudoinverse of a matrix Givens plane rotation

2-80

Functions Supported for Code Generation — Categorical List

Function
prod qr randperm rank rcond repmat reshape rosser rot90 shiftdim sign size sort sortrows squeeze sub2ind subspace sum toeplitz trace tril triu true vander wilkinson zeros

Description Product of array element Orthogonal-triangular decomposition Random permutation Rank of matrix Matrix reciprocal condition number estimate Replicate and tile an array Reshape one array into the dimensions of another Classic symmetric eigenvalue test problem Rotate matrix 90 degrees Shift dimensions Signum function Return the size of a matrix Sort elements in ascending or descending order Sort rows in ascending order Remove singleton dimensions Single index from subscripts Angle between two subspaces Sum of matrix elements Toeplitz matrix Sum of diagonal elements Extract lower triangular part Extract upper triangular part Return an array of logical (Boolean) 1s for the specified dimensions Vandermonde matrix Wilkinson’s eigenvalue test matrix Create a matrix of all zeros

2-81

2

Functions Supported for Code Generation

Nonlinear Numerical Methods
Function
fzero quad2d quadgk

Description Find root of continuous function of one variable Numerically evaluate double integral over planar region Numerically evaluate integral, adaptive Gauss-Kronrod quadrature

Polynomial Functions
Function
poly polyfit polyval roots

Description Polynomial with specified roots Polynomial curve fitting Polynomial evaluation Polynomial roots

Relational Operator Functions
Function
eq ge gt le lt ne

Description Equal (==) Greater than or equal to (>=) Greater than (>) Less than or equal to (<=) Less than (<) Not equal (~=)

2-82

Functions Supported for Code Generation — Categorical List

Rounding and Remainder Functions
Function
ceil ceil convergent fix fix floor floor mod nearest rem round round

Description Round toward plus infinity Round toward positive infinity Round toward nearest integer with ties rounding to nearest even integer Round toward zero Round toward zero Round toward minus infinity Round toward negative infinity Modulus (signed remainder after division) Round toward nearest integer with ties rounding toward positive infinity Remainder after division Round toward nearest integer Round fi object toward nearest integer or round input data using quantizer object

Set Functions
Function
intersect ismember issorted setdiff setxor union unique

Description Find set intersection of two vectors Array elements that are members of set Determine whether set elements are in sorted order Find set difference of two vectors Find set exclusive OR of two vectors Find set union of two vectors Find unique elements of vector

2-83

2

Functions Supported for Code Generation

Signal Processing Functions in MATLAB
Function
chol conv fft fft2 fftn fftshift filter freqspace ifft ifft2 ifftn ifftshift svd

Description Cholesky factorization Convolution and polynomial multiplication Discrete Fourier transform 2-D discrete Fourier transform N-D discrete Fourier transform Shift zero-frequency component to center of spectrum Filter a data sequence using a digital filter that works for both real and complex inputs Frequency spacing for frequency response Inverse discrete Fourier transform 2-D inverse discrete Fourier transform N-D inverse discrete Fourier transform Inverse discrete Fourier transform shift Singular value decomposition

zp2tf

Convert zero-pole-gain filter parameters to transfer function form

Signal Processing Toolbox Functions
Note All of these functions require a DSP System Toolbox license to generate code.

2-84

Functions Supported for Code Generation — Categorical List

Note Many Signal Processing Toolbox functions require constant inputs in generated code. To specify a constant input for codegen, use coder.Constant. For more information, see the “MATLAB Coder” documentation. Function
barthannwin bartlett besselap bitrevorder blackman blackmanharris bohmanwin buttap butter buttord cfirpm cheb1ap cheb2ap cheb1ord

Remarks/Limitations Window length must be a constant. Expressions or variables are allowed if their values do not change. Window length must be a constant. Expressions or variables are allowed if their values do not change. Filter order must be a constant. Expressions or variables are allowed if their values do not change. — Window length must be a constant. Expressions or variables are allowed if their values do not change. Window length must be a constant. Expressions or variables are allowed if their values do not change. Window length must be a constant. Expressions or variables are allowed if their values do not change. Filter order must be a constant. Expressions or variables are allowed if their values do not change. Filter coefficients must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change.

2-85

2

Functions Supported for Code Generation

Function
cheb2ord chebwin cheby1 cheby2 dct

Remarks/Limitations All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All Inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. Length of transform dimension must be a power of two. If specified, the pad or truncation value must be constant. Expressions or variables are allowed if their values do not change. — All inputs must be constants. Expressions or variables are allowed if their values do not change. Inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. Filter coefficients must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change.

downsample dpss ellip ellipap ellipord filtfilt fir1 fir2 fircls fircls1

2-86

Functions Supported for Code Generation — Categorical List

Function
firls firpm firpmord firrcos flattopwin freqz gaussfir gausswin hamming hann idct

Remarks/Limitations All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change. All inputs must be constants. Expressions or variables are allowed if their values do not change.
freqz with no output arguments produces a plot only when the function call terminates in a semicolon. See “freqz With No Output Arguments”.

All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. Length of transform dimension must be a power of two. If specified, the pad or truncation value must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. — If specified, the order of recursion must be a constant. Expressions or variables are allowed if their values do not change.

intfilt kaiser kaiserord levinson

2-87

2

Functions Supported for Code Generation

Function
maxflat nuttallwin parzenwin rectwin resample

Remarks/Limitations All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. The upsampling and downsampling factors must be specified as constants. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. — All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. All inputs must be constant. Expressions or variables are allowed if their values do not change. ? Filter coefficients, upsampling factor, and downsampling factor must be constants. Expressions or variables are allowed if their values do not change. ? Variable-size inputs are not supported. Either declare input n as constant, or use the assert function in the calling function to set upper bounds for n. For example,
assert(n<10)

sgolay sosfilt taylorwin triang tukeywin upfirdn

upsample

xcorr yulewalk

— If specified, the order of recursion must be a constant. Expressions or variables are allowed if their values do not change.

2-88

Functions Supported for Code Generation — Categorical List

Special Values
Symbol
eps inf intmax intmin

Description Floating-point relative accuracy IEEE? arithmetic representation for positive infinity Largest possible value of specified integer type Smallest possible value of specified integer type Not a number Ratio of the circumference to the diameter for a circle Uniformly distributed pseudorandom numbers Normally distributed random numbers Largest positive floating-point number Smallest positive floating-point number

NaN or nan
pi rand randn realmax realmin

Specialized Math
Symbol
beta betainc betaln ellipke erf erfc erfcinv erfcx erfinv expint gamma

Description Beta function Incomplete beta function Logarithm of beta function Complete elliptic integrals of first and second kind Error function Complementary error function Inverse of complementary error function Scaled complementary error function Inverse error function Exponential integral Gamma function

2-89

2

Functions Supported for Code Generation

Symbol
gammainc gammaln

Description Incomplete gamma function Logarithm of the gamma function

Statistical Functions
Function
corrcoef mean median mode std var

Description Correlation coefficients Average or mean value of array Median value of array Most frequent values in array Standard deviation Variance

String Functions
Function
bin2dec bitmax blanks char hex2dec ischar strcmp

Description Convert binary number string to decimal number Maximum double-precision floating-point integer Create string of blank characters Create character array (string) Convert hexadecimal number string to decimal number True for character array (string) Return a logical result for the comparison of two strings; limited to strings known at compile time

2-90

Functions Supported for Code Generation — Categorical List

Structure Functions
Function
isfield struct isstruct

Description Determine whether input is structure array field Create structure Determine whether input is a structure

Trigonometric Functions
Function
acos acosd acosh acot acotd acoth acsc acscd acsch asec asecd asech asin asinh atan atan2 atand atanh

Description Inverse cosine Inverse cosine; result in degrees Inverse hyperbolic cosine Inverse cotangent; result in radians Inverse cotangent; result in degrees Inverse hyperbolic cotangent Inverse cosecant; result in radians Inverse cosecant; result in degrees Inverse cosecant and inverse hyperbolic cosecant Inverse secant; result in radians Inverse secant; result in degrees Inverse hyperbolic secant Inverse sine Inverse hyperbolic sine Inverse tangent Four quadrant inverse tangent Inverse tangent; result in degrees Inverse hyperbolic tangent

2-91

2

Functions Supported for Code Generation

Function
cos cosd cosh cot cotd coth csc cscd csch hypot sec secd sech sin sind sinh tan tand tanh

Description Cosine Cosine; result in degrees Hyperbolic cosine Cotangent; result in radians Cotangent; result in degrees Hyperbolic cotangent Cosecant; result in radians Cosecant; result in degrees Hyperbolic cosecant Square root of sum of squares Secant; result in radians Secant; result in degrees Hyperbolic secant Sine Sine; result in degrees Hyperbolic sine Tangent Tangent; result in degrees Hyperbolic tangent

2-92

3
System Objects Supported for Code Generation
? “About Code Generation for System Objects” on page 3-2 ? “Computer Vision System Toolbox System Objects” on page 3-3 ? “Communications System Toolbox System Objects” on page 3-7 ? “DSP System Toolbox System Objects” on page 3-13

3

System Objects Supported for Code Generation

About Code Generation for System Objects
You can generate C/C++ code for a subset of System objects provided by Communications System Toolbox, DSP System Toolbox, and Computer Vision System Toolbox. To use these System objects, you need to install the appropriate toolbox. System objects are MATLAB object-oriented implementations of algorithms. They extend MATLAB by enabling you to model dynamic systems represented by time-varying algorithms. System objects are well integrated into the MATLAB language, regardless of whether you are writing simple functions, working interactively in the command window, or creating large applications. In contrast to MATLAB functions, System objects automatically manage state information, data indexing, and buffering, which is particularly useful for iterative computations or stream data processing. This enables efficient processing of long data sets. For general information on MATLAB objects, see Object-Oriented Programming in the MATLAB documentation.

3-2

Computer Vision System Toolbox? System Objects

Computer Vision System Toolbox System Objects
If you install Computer Vision System Toolbox software, you can generate C/C++ code for the following Computer Vision System Toolbox System objects. For more information on how to use these System objects, see “Use System Objects for Code Generation from MATLAB” in the Computer Vision System Toolbox documentation. Supported Computer Vision System Toolbox System Objects Object Analysis & Enhancement
vision.BoundaryTracer vision.ContrastAdjuster vision.Deinterlacer vision.EdgeDetector vision.ForegroundDetector vision.HistogramEqualizer vision.TemplateMatcher

Description Trace object boundaries in binary images Adjust image contrast by linear scaling Remove motion artifacts by deinterlacing input video signal Find edges of objects in images Detect foreground using Gaussian Mixture Models Enhance contrast of images using histogram equalization Perform template matching by shifting template over image Convert intensity image to binary image Downsample or upsample chrominance components of images Convert color information between color spaces Demosaic Bayer’s format images Apply or remove gamma correction from images or video streams

Conversions
vision.Autothresholder vision.ChromaResampler vision.ColorSpaceConverter vision.DemosaicInterpolator vision.GammaCorrector

3-3

3

System Objects Supported for Code Generation

Supported Computer Vision System Toolbox System Objects (Continued) Object
vision.ImageComplementer vision.ImageDataTypeConverter

Description Compute complement of pixel values in binary, intensity, or RGB images Convert and scale input image to specified output data type Compute 2-D discrete convolution of two input matrices Perform 2-D FIR filtering of input matrix 2D median filtering Rotate image by specified angle Enlarge or shrink image size

Filtering
vision.Convolver vision.ImageFilter vision.MedianFilter

Geometric Transformations
vision.GeometricRotator vision.GeometricRotator

vision.GeometricScaler

Shift rows or columns of image by linearly varying offset Apply projective or affine transformation to an image Estimate geometric transformation from matching point pairs Translate image in two-dimensional plane using displacement vector Label and count the connected regions in a binary image Perform morphological closing on image Perform morphological dilation on an image

vision.GeometricTransformer

vision.GeometricTransformEstimator vision.GeometricTranslator

Morphological Operations
vision.ConnectedComponentLabeler vision.MorphologicalClose vision.MorphologicalDilate

3-4

Computer Vision System Toolbox? System Objects

Supported Computer Vision System Toolbox System Objects (Continued) Object
vision.MorphologicalErode vision.MorphologicalOpen

Description Perform morphological erosion on an image Perform morphological opening on an image

Sinks
vision.DeployableVideoPlayer

Send video data to computer screen Write video frames and audio samples to multimedia file Read video frames and audio samples from compressed multimedia file

vision.VideoFileWriter

Sources
vision.VideoFileReader

Statistics
vision.Autocorrelator vision.BlobAnalysis vision.Crosscorrelator vision.Histogram vision.LocalMaximaFinder vision.Maximum vision.Mean vision.Median vision.Minimum

Compute 2-D autocorrelation of input matrix Compute statistics for connected regions in a binary image Compute 2-D cross-correlation of two input matrices Generate histogram of each input matrix Find local maxima in matrices Find maximum values in input or sequence of inputs Find mean value of input or sequence of inputs Find median values in an input Find minimum values in input or sequence of inputs

3-5

3

System Objects Supported for Code Generation

Supported Computer Vision System Toolbox System Objects (Continued) Object
vision.PSNR vision.StandardDeviation vision.Variance

Description Compute peak signal-to-noise ratio (PSNR) between images Find standard deviation of input or sequence of inputs Find variance values in an input or sequence of inputs Combine images, overlay images, or highlight selected pixels Draw markers on output image Draw rectangles, lines, polygons, or circles on images Draw text on image or video stream Compute 2-D discrete cosine transform Two-dimensional discrete Fourier transform Find Cartesian coordinates of lines that are described by rho and theta pairs Find lines in images via Hough transform Compute 2-D inverse discrete cosine transform Two–dimensional inverse discrete Fourier transform Perform Gaussian pyramid decomposition Pad or crop input image along its rows, columns, or both

Text & Graphics
vision.AlphaBlender vision.MarkerInserter vision.ShapeInserter vision.TextInserter

Transforms
vision.DCT vision.FFT vision.HoughLines vision.HoughTransform vision.IDCT vision.IFFT vision.Pyramid

Utilities
vision.ImagePadder

3-6

Communications System Toolbox? System Objects

Communications System Toolbox System Objects
If you install Communications System Toolbox software, you can generate C/C++ code for the following Communications System Toolbox System objects. For information on how to use these System objects, see “Generating Code for Communications System Objects” in the Communications System Toolbox documentation. Supported Communications System Toolbox System Objects Object Source Coding
comm.DifferentialDecoder comm.DifferentialEncoder

Description Decode binary signal using differential decoding Encode binary signal using differential coding Add white Gaussian noise to input signal Introduce binary errors Equalize using maximum likelihood sequence estimation Integrate discrete-time signal with periodic resets Measure error vector magnitude Measure modulation error ratio Generate Barker code Generate Hadamard code Generate a Kasami sequence Generate OVSF code

Channels
comm.AWGNChannel comm.BinarySymmetricChannel

Equalizers
comm.MLSEEqualizer

Filters
comm.IntegrateAndDumpFilter

Measurements
comm.EVM comm.MER

Sources
comm.BarkerCode comm.HadamardCode comm.KasamiSequence comm.OVSFCode

3-7

3

System Objects Supported for Code Generation

Supported Communications System Toolbox System Objects (Continued) Object
comm.PNSequence comm.WalshCode

Description Generate a pseudo-noise (PN) sequence Generate Walsh code from orthogonal set of codes Convolutionally encode binary data Decode convolutionally encoded data using Viterbi algorithm Detect errors in input data using cyclic redundancy code Generate cyclic redundancy code bits and append to input data Decode input signal using parallel concatenated decoding scheme Encode input signal using parallel concatenated encoding scheme Deinterleave input symbols using algebraically derived permutation vector Permute input symbols using an algebraically derived permutation vector Deinterleave input symbols using permutation vector Permute input symbols using a permutation vector Deinterleave input symbols using permutation matrix Permute input symbols using permutation matrix Deinterleave input symbols by filling a matrix along diagonals

Error Detection and Correction – Convolutional Coding
comm.ConvolutionalEncoder comm.ViterbiDecoder

Error Detection and Correction – Cyclic Redundancy Check Coding
comm.CRCDetector comm.CRCGenerator comm.TurboDecoder comm.TurboEncoder

Interleavers – Block
comm.AlgebraicDeinterleaver comm.AlgebraicInterleaver comm.BlockDeinterleaver comm.BlockInterleaver comm.MatrixDeinterleaver comm.MatrixInterleaver comm.MatrixHelicalScanDeinterleaver

3-8

Communications System Toolbox? System Objects

Supported Communications System Toolbox System Objects (Continued) Object
comm.MatrixHelicalScanInterleaver

Description Permute input symbols by selecting matrix elements along diagonals Restore ordering of symbols using shift registers Permute input symbols using shift registers Restore ordering of symbols using a helical array Permute input symbols using a helical array Restore ordering of symbols using a set of shift registers with specified delays Permute input symbols using a set of shift registers with specified delays Combine inputs using orthogonal space-time block code Encode input message using orthogonal space-time block code Demodulate using binary PSK method Modulate using binary PSK method Modulate using differential binary PSK method Demodulate using M-ary DPSK method Modulate using M-ary DPSK method Demodulate using differential quadrature PSK method Modulate using differential quadrature PSK method Demodulate using M-ary DPSK method Demodulate using quadrature PSK method

Interleavers – Convolutional
comm.ConvolutionalDeinterleaver comm.ConvolutionalInterleaver comm.HelicalDeinterleaver comm.HelicalInterleaver comm.MultiplexedDeinterleaver comm.MultiplexedInterleaver

MIMO
comm.OSTBCCombiner comm.OSTBCEncoder

Digital Baseband Modulation – Phase
comm.BPSKDemodulator comm.BPSKModulator comm.DBPSKModulator comm.DPSKDemodulator comm.DPSKModulator comm.DQPSKDemodulator comm.DQPSKModulator comm.DBPSKDemodulator comm.QPSKDemodulator

3-9

3

System Objects Supported for Code Generation

Supported Communications System Toolbox System Objects (Continued) Object
comm.QPSKModulator comm.PSKDemodulator comm.PSKModulator comm.OQPSKDemodulator comm.OQPSKModulator

Description Modulate using quadrature PSK method Demodulate using M-ary PSK method Modulate using M-ary PSK method Demodulate offset quadrature PSK modulated data Modulate using offset quadrature PSK method Demodulate using arbitrary QAM constellation Modulate using arbitrary QAM constellation Demodulate using M-ary PAM method Modulate using M-ary PAM method Demodulate using rectangular QAM method Modulate using rectangular QAM method Demodulate using M-ary FSK method Modulate using M-ary FSK method Demodulate convolutionally encoded data mapped to arbitrary QAM constellation Convolutionally encode binary data and map using arbitrary QAM constellation Demodulate convolutionally encoded data mapped to M-ary PSK constellation Convolutionally encode binary data and map using M-ary PSK constellation Demodulate convolutionally encoded data mapped to rectangular QAM constellation

Digital Baseband Modulation – Amplitude
comm.GeneralQAMDemodulator comm.GeneralQAMModulator comm.PAMDemodulator comm.PAMModulator comm.RectangularQAMDemodulator comm.RectangularQAMModulator

Digital Baseband Modulation – Frequency
comm.FSKDemodulator comm.FSKModulator

Digital Baseband Modulation – Trelllis Coded
comm.GeneralQAMTCMDemodulator comm.GeneralQAMTCMModulator comm.PSKTCMDemodulator comm.PSKTCMModulator comm.RectangularQAMTCMDemodulator

3-10

Communications System Toolbox? System Objects

Supported Communications System Toolbox System Objects (Continued) Object
comm.RectangularQAMTCMModulator

Description Convolutionally encode binary data and map using rectangular QAM constellation Demodulate using CPFSK method and Viterbi algorithm Modulate using CPFSK method Demodulate using CPM method and Viterbi algorithm Modulate using CPM method Demodulate using GMSK method and the Viterbi algorithm Modulate using GMSK method Demodulate using MSK method and the Viterbi algorithm Modulate using MSK method Apply phase and frequency offsets to input signal

Digital Baseband Modulation – Continuous Phase
comm.CPFSKDemodulator comm.CPFSKModulator comm.CPMDemodulator comm.CPMModulator comm.GMSKDemodulator comm.GMSKModulator comm.MSKDemodulator comm.MSKModulator

RF Impairments
comm.PhaseFrequencyOffset

Synchronization – Timing Phase
comm.EarlyLateGateTimingSynchronizer Recover symbol timing phase using early-late gate

method
comm.GardnerTimingSynchronizer comm.GMSKTimingSynchronizer comm.MSKTimingSynchronizer

Recover symbol timing phase using Gardner’s method Recover symbol timing phase using fourth-order nonlinearity method Recover symbol timing phase using fourth-order nonlinearity method method

comm.MuellerMullerTimingSynchronizer Recover symbol timing phase using Mueller-Muller

3-11

3

System Objects Supported for Code Generation

Supported Communications System Toolbox System Objects (Continued) Object Synchronization Utilities
comm.DiscreteTimeVCO

Description Generate variable frequency sinusoid Convert vector of bits to vector of integers Convert vector of integers to vector of bits Descramble input signal Scramble input signal

Converters
comm.BitToInteger comm.IntegerToBit

Sequence Operators
comm.Descrambler comm.Scrambler

3-12

DSP System Toolbox? System Objects

DSP System Toolbox System Objects
If you install DSP System Toolbox software, you can generate C/C++ code for the following DSP System Toolbox System objects. For information on how to use these System objects, see “Code Generation with System Objects” in the DSP System Toolbox documentation. Supported DSP System Toolbox System Objects Object Estimation
dsp.BurgAREstimator dsp.BurgSpectrumEstimator

Description Compute estimate of autoregressive model parameters using Burg method Compute parametric spectral estimate using Burg method Note For code generation, you cannot call the reset method before calling the step method.

dsp.CepstralToLPC dsp.LevinsonSolver dsp.LPCToAutocorrelation dsp.LPCToCepstral dsp.LPCToLSF dsp.LPCToLSP dsp.LPCToRC

Convert cepstral coefficients to linear prediction coefficients Solve linear system of equations using Levinson-Durbin recursion Convert linear prediction coefficients to autocorrelation coefficients Convert linear prediction coefficients to cepstral coefficients Convert linear prediction coefficients to line spectral frequencies Convert linear prediction coefficients to line spectral pairs Convert linear prediction coefficients to reflection coefficients

3-13

3

System Objects Supported for Code Generation

Supported DSP System Toolbox System Objects (Continued) Object
dsp.LSFToLPC dsp.LSPToLPC

Description Convert line spectral frequencies to linear prediction coefficients Convert line spectral pairs to linear prediction coefficients Convert reflection coefficients to autocorrelation coefficients Convert reflection coefficients to linear prediction coefficients Model biquadratic IIR (SOS) filters Filter each channel of input over time using discrete-time filter implementations Upsample and filter input signals Upsample, filter and downsample input signals Compute output, error, and weights using LMS adaptive algorithm Add vector to array along specified dimension Divide array by vector along specified dimension Multiply array by vector along specified dimension Subtract vector from array along specified dimension Compute cumulative product of channel, column, or row elements Compute cumulative sum of channel, column, or row elements Factor square Hermitian positive definite matrices into lower, upper, and diagonal components

dsp.RCToAutocorrelation dsp.RCToLPC

Filters
dsp.BiquadFilter dsp.DigitalFilter dsp.FIRInterpolator dsp.FIRRateConverter dsp.LMSFilter

Math Operations
dsp.ArrayVectorAdder dsp.ArrayVectorDivider dsp.ArrayVectorMultiplier dsp.ArrayVectorSubtractor dsp.CumulativeProduct dsp.CumulativeSum dsp.LDLFactor

3-14

DSP System Toolbox? System Objects

Supported DSP System Toolbox System Objects (Continued) Object
dsp.LevinsonSolver dsp.LowerTriangularSolver dsp.LUFactor dsp.Normalizer dsp.UpperTriangularSolver

Description Solve linear system of equations using Levinson-Durbin recursion Solve LX = B for X when L is lower triangular matrix Factor square matrix into lower and upper triangular matrices Normalize input Solve UX = B for X when U is upper triangular matrix

Quantizers
dsp.ScalarQuantizerDecoder dsp.ScalarQuantizerEncoder dsp.VectorQuantizerDecoder dsp.VectorQuantizerEncoder

Convert each index value into quantized output value Perform scalar quantization encoding Find vector quantizer codeword for given index value Perform vector quantization encoding Count up or down through specified range of numbers Rebuffer sequence of inputs with one-sample shift Compute convolution of two inputs Delay input by specified number of samples or frames Interpolate values of real input samples Generate real or complex sinusoidal signals Determine extrema (maxima or minima) in input signal Unwrap signal phase Delay input by time-varying fractional number of sample periods

Signal Management
dsp.Counter dsp.DelayLine

Signal Operations
dsp.Convolver dsp.Delay dsp.Interpolator dsp.NCO dsp.PeakFinder dsp.PhaseUnwrapper dsp.VariableFractionalDelay

3-15

3

System Objects Supported for Code Generation

Supported DSP System Toolbox System Objects (Continued) Object
dsp.VariableIntegerDelay dsp.Window dsp.ZeroCrossingDetector

Description Delay input by time-varying integer number of sample periods Generate or apply window function Calculate number of zero crossings of a signal Write audio data to computer’s audio device Write audio file Send UDP packets to the network Read audio samples from an audio file Read audio data from computer’s audio device

Signal Processing Sinks
dsp.AudioPlayer dsp.AudioFileWriter dsp.UDPSender

Signal Processing Sources
dsp.AudioFileReader dsp.AudioRecorder

dsp.UDPReceiver dsp.SineWave

Receive UDP packets from the network Generate discrete sine wave Compute autocorrelation of vector inputs Compute cross-correlation of two inputs Output histogram of an input or sequence of inputs Compute maximum value in input Compute average or mean value in input Compute median value in input Compute minimum value in input Compute root-mean-square of vector elements Compute standard deviation of vector elements

Statistics
dsp.Autocorrelator dsp.Crosscorrelator dsp.Histogram dsp.Maximum dsp.Mean dsp.Median dsp.Minimum dsp.RMS dsp.StandardDeviation

3-16

DSP System Toolbox? System Objects

Supported DSP System Toolbox System Objects (Continued) Object
dsp.Variance

Description Compute variance of input or sequence of inputs Compute analytic signals of discrete-time inputs Note For code generation, you cannot call the reset method before calling the step method.

Transforms
dsp.AnalyticSignal

dsp.DCT dsp.FFT dsp.IDCT

Compute discrete cosine transform (DCT) of input Compute fast Fourier transform (FFT) of input Compute inverse discrete cosine transform (IDCT) of input Compute inverse fast Fourier transform (IFFT) of input

dsp.IFFT

3-17

3

System Objects Supported for Code Generation

3-18

4
Defining MATLAB Variables for C/C++ Code Generation
? “Why Define Variables Differently for Code Generation?” on page 4-2 ? “Best Practices for Defining Variables for C/C++ Code Generation” on page 4-3 ? “When You Can Reassign Variable Properties for C/C++ Code Generation” on page 4-7 ? “Eliminating Redundant Copies of Variables in Generated Code” on page 4-8 ? “Defining and Initializing Persistent Variables” on page 4-10 ? “Reusing the Same Variable with Different Properties” on page 4-11 ? “Supported Variable Types” on page 4-16

4

Defining MATLAB? Variables for C/C++ Code Generation

Why Define Variables Differently for Code Generation?
In the MATLAB language, variables can change their properties dynamically at run time so you can use the same variable to hold a value of any class, size, or complexity. For example, the following code works in MATLAB:
function x = foo(c) %#codegen coder.extrinsic('disp'); if(c>0) x = int8(0); else x = [1 2 3]; end disp(x); end

However, statically-typed languages like C must be able to determine variable properties at compile time. Therefore, for C/C++ code generation, you must explicitly define the class, size, and complexity of variables in MATLAB source code before using them. For example, rewrite the above source code with a definition for x:
function x = foo(c) %#codegen coder.extrinsic('disp'); x = zeros(1,3); if(c>0) x = int8(0); else x = [1 2 3]; end disp(x); end

For more information, see “Best Practices for Defining Variables for C/C++ Code Generation” on page 4-3.

4-2

Best Practices for Defining Variables for C/C++ Code Generation

Best Practices for Defining Variables for C/C++ Code Generation
In this section... “Define Variables By Assignment Before Using Them” on page 4-3 “Use Caution When Reassigning Variables” on page 4-6 “Use Type Cast Operators in Variable Definitions” on page 4-6 “Define Matrices Before Assigning Indexed Variables” on page 4-6

Define Variables By Assignment Before Using Them
For C/C++ code generation, you should explicitly and unambiguously define the class, size, and complexity of variables before using them in operations or returning them as outputs. Define variables by assignment, but note that the assignment copies not only the value, but also the size, class, and complexity represented by that value to the new variable. For example: Assignment:
a = 14.7; b = a; c = zeros(5,2); d = [1 2 3 4 5; 6 7 8 9 0]; y = int16(3);

Defines:
a as a real double scalar. b with properties of a (real double

scalar).
c as a real 5-by-2 array of doubles. d as a real 5-by-2 array of doubles. y as a real 16-bit integer scalar.

Define properties this way so that the variable is defined on all execution paths during C/C++ code generation (see Example: Defining a Variable for Multiple Execution Paths on page 4-4). The data that you assign to a variable can be a scalar, matrix, or structure. If your variable is a structure, define the properties of each field explicitly (see Example: Defining All Fields in a Structure on page 4-5).

4-3

4

Defining MATLAB? Variables for C/C++ Code Generation

Initializing the new variable to the value of the assigned data sometimes results in redundant copies in the generated code. To avoid redundant copies, you can define variables without initializing their values by using the coder.nullcopy construct as described in “Eliminating Redundant Copies of Variables in Generated Code” on page 4-8. When you define variables, they are local by default; they do not persist between function calls. To make variables persistent, see “Defining and Initializing Persistent Variables” on page 4-10. Example: Defining a Variable for Multiple Execution Paths Consider the following MATLAB code:
... if c > 0 x = 11; end % Later in your code ... if c > 0 use(x); end ...

Here, x is assigned only if c > 0 and used only when c > 0. This code works in MATLAB, but generates a compilation error during code generation because it detects that x is undefined on some execution paths (when c <= 0),. To make this code suitable for code generation, define x before using it:
x = 0; ... if c > 0 x = 11; end % Later in your code ... if c > 0 use(x); end ...

4-4

Best Practices for Defining Variables for C/C++ Code Generation

Example: Defining All Fields in a Structure Consider the following MATLAB code:
... if c > 0 s.a = 11; disp(s); else s.a = 12; s.b = 12; end % Try to use s use(s); ...

Here, the first part of the if statement uses only the field a, and the else clause uses fields a and b. This code works in MATLAB, but generates a compilation error during C/C++ code generation because it detects a structure type mismatch. To prevent this error, do not add fields to a structure after you perform certain operations on the structure. For more information, see Chapter 6, “Code Generation for MATLAB Structures”. To make this code suitable for C/C++ code generation, define all fields of s before using it.
... % Define all fields in structure s s = struct( a ,0, b , 0); if c > 0 s.a = 11; disp(s); else s.a = 12; s.b = 12; end % Use s use(s); ...

4-5

4

Defining MATLAB? Variables for C/C++ Code Generation

Use Caution When Reassigning Variables
In general, you should adhere to the "one variable/one type" rule for C/C++ code generation; that is, each variable must have a specific class, size and complexity. Generally, if you reassign variable properties after the initial assignment, you get a compilation error during code generation, but there are exceptions, as described in “When You Can Reassign Variable Properties for C/C++ Code Generation” on page 4-7.

Use Type Cast Operators in Variable Definitions
By default, constants are of type double. To define variables of other types, you can use type cast operators in variable definitions. For example, the following code defines variable y as an integer:
... x = 15; % x is of type double by default. y = uint8(x); % z has the value of x, but cast to uint8. ...

Define Matrices Before Assigning Indexed Variables
When generating C/C++ code from MATLAB, you cannot grow a variable by writing into an element beyond its current size. Such indexing operations produce run-time errors. You must define the matrix first before assigning values to any of its elements. For example, the following initial assignment is not allowed for code generation:
g(3,2) = 14.6; % Not allowed for creating g % OK for assigning value once created

For more information about indexing matrices, see “Limitations on Matrix Indexing Operations for Code Generation” on page 8-40.

4-6

When You Can Reassign Variable Properties for C/C++ Code Generation

When You Can Reassign Variable Properties for C/C++ Code Generation
There are certain variables that you can reassign after the initial assignment with a value of different class, size, or complexity: Dynamically sized variables A variable can hold values that have the same class and complexity but different sizes. If the size of the initial assignment is not constant, the variable is dynamically sized in generated code. For more information, see “How Working with Variable-Size Data Is Different for Code Generation” on page 8-3. Variables reused in the code for different purposes You can reassign the type (class, size, and complexity) of a variable after the initial assignment if each occurrence of the variable can have only one type. In this case, the variable is renamed in the generated code to create multiple independent variables. For more information, see “Reusing the Same Variable with Different Properties” on page 4-11.

4-7

4

Defining MATLAB? Variables for C/C++ Code Generation

Eliminating Redundant Copies of Variables in Generated Code
In this section... “When Redundant Copies Occur” on page 4-8 “How to Eliminate Redundant Copies by Defining Uninitialized Variables” on page 4-8 “Defining Uninitialized Variables” on page 4-9

When Redundant Copies Occur
During C/C++ code generation, MATLAB checks for statements that attempt to access uninitialized memory. If it detects execution paths where a variable is used but is potentially not defined, it generates a compile-time error. To prevent these errors, define all variables by assignment before using them in operations or returning them as function outputs. Note, however, that variable assignments not only copy the properties of the assigned data to the new variable, but also initialize the new variable to the assigned value. This forced initialization sometimes results in redundant copies in C/C++ code. To eliminate redundant copies, define uninitialized variables by using the coder.nullcopy function, as described in “How to Eliminate Redundant Copies by Defining Uninitialized Variables” on page 4-8..

How to Eliminate Redundant Copies by Defining Uninitialized Variables
1 Define the variable with coder.nullcopy. 2 Initialize the variable before reading it.

When the uninitialized variable is an array, you must initialize all of its elements before passing the array as an input to a function or operator — even if the function or operator does not read from the uninitialized portion of the array.

4-8

Eliminating Redundant Copies of Variables in Generated Code

What happens if you access uninitialized data? Uninitialized memory contains arbitrary values. Therefore, accessing uninitialized data may lead to segmentation violations or nondeterministic program behavior (different runs of the same program may yield inconsistent results).

Defining Uninitialized Variables
In the following code, the assignment statement X = zeros(1,N) not only defines X to be a 1-by-5 vector of real doubles, but also initializes each element of X to zero.
function X = fcn %#codegen N = 5; X = zeros(1,N); for i = 1:N if mod(i,2) == 0 X(i) = i; else X(i) = 0; end end

This forced initialization creates an extra copy in the generated code. To eliminate this overhead, use coder.nullcopy in the definition of X:
function X = fcn2 %#codegen N = 5; X = coder.nullcopy(zeros(1,N)); for i = 1:N if mod(i,2) == 0 X(i) = i; else X(i) = 0; end end

4-9

4

Defining MATLAB? Variables for C/C++ Code Generation

Defining and Initializing Persistent Variables
Persistent variables are local to the function in which they are defined, but they retain their values in memory between calls to the function. To define persistent variables for C/C++ code generation, use the persistent statement, as in this example:
persistent PROD_X;

The definition should appear at the top of the function body, after the header and comments, but before the first use of the variable. During code generation, the value of the persistent variable is initialized to an empty matrix by default. You can assign your own value after the definition by using the isempty statement, as in this example:
function findProduct(inputvalue) %#codegen persistent PROD_X if isempty(PROD_X) PROD_X = 1; end PROD_X = PROD_X * inputvalue; end

For more information, see Persistent Variables in the MATLAB Programming Fundamentals documentation.

4-10

Reusing the Same Variable with Different Properties

Reusing the Same Variable with Different Properties
In this section... “When You Can Reuse the Same Variable with Different Properties” on page 4-11 “When You Cannot Reuse Variables” on page 4-12 “Limitations of Variable Reuse” on page 4-14

When You Can Reuse the Same Variable with Different Properties
You can reuse (reassign) an input, output, or local variable with different class, size, or complexity if MATLAB can unambiguously determine the properties of each occurrence of this variable during C/C++ code generation. If so, MATLAB creates separate uniquely named local variables in the generated code. You can view these renamed variables in the code generation report (see “Viewing Variables in Your MATLAB Code” in the MATLAB Coder documentation. A common example of variable reuse is in if-elseif-else or switch-case statements. For example, the following function example1 first uses the variable t in an if statement, where it holds a scalar double, then reuses t outside the if statement to hold a vector of doubles.
function y = example1(u) %#codegen if all(all(u>0)) % First, t is used to hold a scalar double value t = mean(mean(u)) / numel(u); u = u - t; end % t is reused to hold a vector of doubles t = find(u > 0); y = sum(u(t(2:end-1)));

To compile this example and see how MATLAB renames the reused variable t, see Variable Reuse in an if Statement on page 4-12.

4-11

4

Defining MATLAB? Variables for C/C++ Code Generation

When You Cannot Reuse Variables
You cannot reuse (reassign) variables if it is not possible to determine the class, size, and complexity of an occurrence of a variable unambiguously during code generation. In this case, variables cannot be renamed and a compilation error occurs. For example, the following example2 function assigns a fixed-point value to x in the if statement and reuses x to store a matrix of doubles in the else clause. It then uses x after the if-else statement. This function generates a compilation error because after the if-else statement, variable x can have different properties depending on which if-else clause executes.
function y = example2(use_fixpoint, data) %#codegen if use_fixpoint % x is fixed-point x = fi(data, 1, 12, 3); else % x is a matrix of doubles x = data; end % When x is reused here, it is not possible to determine its % class, size, and complexity t = sum(sum(x)); y = t > 0; end

Variable Reuse in an if Statement To see how MATLAB renames a reused variable t:
1 Create a MATLAB file example1.m containing the following code.

function y = example1(u) %#codegen if all(all(u>0)) % First, t is used to hold a scalar double value t = mean(mean(u)) / numel(u); u = u - t; end % t is reused to hold a vector of doubles t = find(u > 0);

4-12

Reusing the Same Variable with Different Properties

y = sum(u(t(2:end-1))); end
2 Compile example1.

For example, to generate a MEX function, enter:
codegen -o example1x -report example1.m -args {ones(5,5)}

Note codegen requires a MATLAB Coder license.
codegen reports that the compilation was successful. It generates a MEX function, example1x in the current folder, and provides a link to the code

generation report.
3 Open the code generation report. 4 In the MATLAB code pane of the code generation report, place your pointer

over the variable t inside the if statement. The code generation report highlights both instances of t in the if statement because they share the same class, size, and complexity. It displays the data type information for t at this point in the code. Here, t is a scalar double.

5 In the MATLAB code pane of the report, place your pointer over the

variable t outside the for-loop.

4-13

4

Defining MATLAB? Variables for C/C++ Code Generation

This time, the report highlights both instances of t outside the if statement. The report indicates that t might hold up to 25 doubles. The size of t is :25, that is, a column vector containing a maximum of 25 doubles.

6 Click the Variables tab to view the list of variables used in example1.

The report displays a list of all the variables in example1. There are two uniquely named local variables t>1 and t>2.
7 In the list of variables, place your pointer over t>1.

The code generation report highlights both instances of t in the if statement.
8 In the list of variables, place your pointer over t>2

The code generation report highlights both instances of t outside the if statement.

Limitations of Variable Reuse
The following variables cannot be renamed in generated code: ? Persistent variables. ? Global variables. ? Variables passed to C code using coder.ref, coder.rref, coder.wref. ? Variables whose size is set using coder.varsize. ? Variables whose names are controlled using coder.cstructname. ? The index variable of a for-loop when it is used inside the loop body.

4-14

Reusing the Same Variable with Different Properties

? The block outputs of a MATLAB Function block in a Simulink model. ? Chart-owned variables of a MATLAB function in a Stateflow chart.

4-15

4

Defining MATLAB? Variables for C/C++ Code Generation

Supported Variable Types
You can use the following data types for C/C++ code generation from MATLAB: Type
char complex double int8, int16, int32 logical single struct uint8, uint16, uint32

Description Character array (string) Complex data. Cast function takes real and imaginary components Double-precision floating point Signed integer Boolean true or false Single-precision floating point Structure (see Chapter 6, “Code Generation for MATLAB Structures”) Unsigned integer See “Code Acceleration and Code Generation from MATLAB for Fixed-Point Algorithms” in the Fixed-Point Toolbox User’s Guide documentation.

Fixed-point

4-16

5
Defining Data for Code Generation
? “How Working with Data is Different for Code Generation” on page 5-2 ? “Code Generation for Complex Data” on page 5-4 ? “Code Generation for Characters” on page 5-6

5

Defining Data for Code Generation

How Working with Data is Different for Code Generation
To generate efficient standalone code, you must use the following types and classes of data differently than you normally would when running your code in the MATLAB environment: Data Complex numbers What’s Different ? Complexity of variables must be set at time of assignment and before first use ? Expressions containing a complex number or variable always evaluate to a complex result, even if the result is zero Characters Enumerated data Restricted to 8 bits of precision ? Supports integer-based enumerated types only ? Restricted use in switch statements and for-loops Function handles ? Function handles must be scalar values ? Same bound variable cannot reference different function handles ? Cannot pass function handles to or from primary or extrinsic functions Chapter 9, “Code Generation for Function Handles” “Code Generation for Characters” on page 5-6 Chapter 7, “Code Generation for Enumerated Data” More Information “Code Generation for Complex Data” on page 5-4

5-2

How Working with Data is Different for Code Generation

Data

What’s Different ? Cannot view function handles from the debugger

More Information

5-3

5

Defining Data for Code Generation

Code Generation for Complex Data
In this section... “Restrictions When Defining Complex Variables” on page 5-4 “Expressions Containing Complex Operands Yield Complex Results” on page 5-5

Restrictions When Defining Complex Variables
For code generation, you must set the complexity of variables at the time of assignment, either by assigning a complex constant or using the complex function, as in these examples:
x = 5 + 6i; % x is a complex number by assignment. y = 7 + 8j; % y is a complex number by assignment. x = complex(5,6); % x is the complex number 5 + 6i.

Once you set the type and size of a variable, you cannot cast it to another type or size. In the following example, the variable x is defined as complex and stays complex:
x = 1 + 2i; % Defines x as a complex variable. y = int16(x); % Real and imaginary parts of y are int16. x = 3; % x now has the value 3 + 0i.

Mismatches can also occur when you assign a real operand the complex result of an operation:
z = 3; % Sets type of z to double (real) z = 3 + 2i; % ERROR: cannot recast z to complex

As a workaround, set the complexity of the operand to match the result of the operation:
m = complex(3); % Sets m to complex variable of value 3 + 0i m = 5 + 6.7i; % Assigns a complex result to a complex number

5-4

Code Generation for Complex Data

Expressions Containing Complex Operands Yield Complex Results
In general, expressions that contain one or more complex operands always produce a complex result in generated code, even if the value of the result is zero. Consider the following example:
x = 2 + 3i; y = 2 - 3i; z = x + y; % z is 4 + 0i.

In MATLAB, this code generates the real result z = 4. However, during code generation, the types for x and y are known, but their values are not. Because either or both operands in this expression are complex, z is defined as a complex variable requiring storage for both a real and an imaginary part. This means that z equals the complex result 4 + 0i in generated code, not 4 as in MATLAB code. There are two exceptions to this behavior: ? Functions that take complex arguments, but produce real results
y = real(x); % y is the real part of the complex number x. y = imag(x); % y is the real-valued imaginary part of x. y = isreal(x); % y is false (0) for a complex number x.

? Functions that take real arguments, but produce complex results:
z = complex(x,y); % z is a complex number for a real x and y.

5-5

5

Defining Data for Code Generation

Code Generation for Characters
The complete set of Unicode? characters is not supported for code generation. Characters are restricted to 8 bits of precision in generated code. Because many mathematical operations require more than 8 bits of precision, it is recommended that you do not perform arithmetic with characters if you intend to generate code from your MATLAB algorithm.

5-6

6
Code Generation for MATLAB Structures
? “How Working with Structures Is Different for Code Generation” on page 6-2 ? “Structure Operations Allowed for Code Generation” on page 6-3 ? “Defining Scalar Structures for Code Generation” on page 6-4 ? “Defining Arrays of Structures for Code Generation” on page 6-7 ? “Making Structures Persistent” on page 6-9 ? “Indexing Substructures and Fields” on page 6-10 ? “Assigning Values to Structures and Fields” on page 6-12 ? “Passing Large Structures as Input Parameters” on page 6-13

6

Code Generation for MATLAB? Structures

How Working with Structures Is Different for Code Generation
To generate efficient standalone code for structures, you must define and use structures differently than you normally would when running your code in the MATLAB environment: What’s Different Use a restricted set of operations. Observe restrictions on properties and values of scalar structures. Make structures uniform in arrays. Reference structure fields individually during indexing. Avoid type mismatch when assigning values to structures and fields. More Information “Structure Operations Allowed for Code Generation” on page 6-3 “Defining Scalar Structures for Code Generation” on page 6-4 “Defining Arrays of Structures for Code Generation” on page 6-7 “Indexing Substructures and Fields” on page 6-10 “Assigning Values to Structures and Fields” on page 6-12

For an introduction to working with structures in MATLAB, see “Structures” in the MATLAB Getting Started documentation.

6-2

Structure Operations Allowed for Code Generation

Structure Operations Allowed for Code Generation
To generate efficient standalone code for MATLAB structures, you are restricted to the following operations: ? Define structures as local and persistent variables by assignment and using the struct function ? Index structure fields using dot notation ? Define primary function inputs as structures ? Pass structures to subfunctions

6-3

6

Code Generation for MATLAB? Structures

Defining Scalar Structures for Code Generation
In this section... “Restrictions When Using struct” on page 6-4 “Restrictions When Defining Scalar Structures by Assignment” on page 6-4 “Adding Fields in Consistent Order on Each Control Flow Path” on page 6-4 “Restriction on Adding New Fields After First Use” on page 6-5

Restrictions When Using struct
When you use the struct function to create scalar structures for code generation, the following restrictions apply: ? Field arguments must be scalar values. ? You cannot create structures of cell arrays.

Restrictions When Defining Scalar Structures by Assignment
When you define a scalar structure by assigning a variable to a preexisting structure, you do not need to define the variable before the assignment. However, if you already defined that variable, it must have the same class, size, and complexity as the structure you assign to it. In the following example, p is defined as a structure that has the same properties as the predefined structure S:
... S = struct('a', p = S; ...

0, 'b',

1, 'c',

2);

Adding Fields in Consistent Order on Each Control Flow Path
When you create a structure, you must add fields in the same order on each control flow path. For example, the following code generates a compiler error because it adds the fields of structure x in a different order in each if statement clause:

6-4

Defining Scalar Structures for Code Generation

function y = fcn(u) %#codegen if u > 0 x.a = 10; x.b = 20; else x.b = 30; % Generates an error (on variable x) x.a = 40; end y = x.a + x.b;

In this example, the assignment to x.a comes before x.b in the first if statement clause, but the assignments appear in reverse order in the else clause. Here is the corrected code:
function y = fcn(u) %#codegen if u > 0 x.a = 10; x.b = 20; else x.a = 40; x.b = 30; end y = x.a + x.b;

Restriction on Adding New Fields After First Use
You cannot add fields to a structure after you perform any of the following operations on the structure: ? Reading from the structure ? Indexing into the structure array ? Passing the structure to a function For example, consider this code:
... x.c = 10; % Defines structure and creates field c y = x; % Reads from structure x.d = 20; % Generates an error ...

6-5

6

Code Generation for MATLAB? Structures

In this example, the attempt to add a new field d after reading from structure x generates an error. This restriction extends across the structure hierarchy. For example, you cannot add a field to a structure after operating on one of its fields or nested structures, as in this example:
function y = fcn(u) %#codegen x.c = 10; y = x.c; x.d = 20; % Generates an error

In this example, the attempt to add a new field d to structure x after reading from the structure’s field c generates an error.

6-6

Defining Arrays of Structures for Code Generation

Defining Arrays of Structures for Code Generation
In this section... “Ensuring Consistency of Fields” on page 6-7 “Using repmat to Define an Array of Structures with Consistent Field Properties” on page 6-7 “Defining an Array of Structures Using Concatenation” on page 6-8

Ensuring Consistency of Fields
When you create an array of MATLAB structures with the intent of generating code, you must be sure that each structure field in the array has the same size, type, and complexity.

Using repmat to Define an Array of Structures with Consistent Field Properties
You can create an array of structures from a scalar structure by using the MATLAB repmat function, which replicates and tiles an existing scalar structure:
1 Create a scalar structure, as described in “Defining Scalar Structures for

Code Generation” on page 6-4.
2 Call repmat, passing the scalar structure and the dimensions of the array. 3 Assign values to each structure using standard array indexing and

structure dot notation. For example, the following code creates X, a 1-by-3 array of scalar structures. Each element of the array is defined by the structure s, which has two fields, a and b:
... s.a = 0; s.b = 0; X = repmat(s,1,3); X(1).a = 1;

6-7

6

Code Generation for MATLAB? Structures

X(2).a X(3).a X(1).b X(2).b X(3).b ...

= = = = =

2; 3; 4; 5; 6;

Defining an Array of Structures Using Concatenation
To create a small array of structures, you can use the concatenation operator, square brackets ( [ ] ), to join one or more structures into an array (see “Concatenating Matrices” in the MATLAB Mathematics documentation). For code generation, all the structures that you concatenate must have the same size, class, and complexity. For example, the following code uses concatenation and a subfunction to create the elements of a 1-by-3 structure array:
... W = [ sab(1,2) sab(2,3) sab(4,5) ]; function s = sab(a,b) s.a = a; s.b = b; ...

6-8

Making Structures Persistent

Making Structures Persistent
To make structures persist, you define them to be persistent variables and initialize them with the isempty statement, as described in “Defining and Initializing Persistent Variables” on page 4-10. For example, the following function defines structure X to be persistent and initializes its fields a and b:
function f(u) persistent X if isempty(X) X.a = 1; X.b = 2; end %#codegen

6-9

6

Code Generation for MATLAB? Structures

Indexing Substructures and Fields
Use these guidelines when indexing substructures and fields for code generation: Reference substructure field values individually using dot notation For example, the following MATLAB code uses dot notation to index fields and substructures:
... substruct1.a1 = 15.2; substruct1.a2 = int8([1 2;3 4]); mystruct = struct('ele1',20.5,'ele2',single(100), 'ele3',substruct1); substruct2 = mystruct; substruct2.ele3.a2 = 2*(substruct1.a2); ...

The generated code indexes elements of the structures in this example by resolving symbols as follows: Dot Notation
substruct1.a1 substruct2.ele3.a1 substruct2.ele3.a2(1,1)

Symbol Resolution Field a1 of local structure substruct1 Value of field a1 of field ele3, a substructure of local structure
substruct2

Value in row 1, column 1 of field a2 of field ele3, a substructure of local structure substruct2

Reference field values individually in structure arrays To reference the value of a field in a structure array, you must index into the array to the structure of interest and then reference that structure’s field individually using dot notation, as in this example:
...

6-10

Indexing Substructures and Fields

y = X(1).a % Extracts the value of field a % of the first structure in array X ...

To reference all the values of a particular field for each structure in an array, use this notation in a for loop, as in this example:
... s.a s.b X = for

= 0; = 0; repmat(s,1,5); i = 1:5 X(i).a = i; X(i).b = i+1;

end

This example uses the repmat function to define an array of structures, each with two fields a and b as defined by s. See “Defining Arrays of Structures for Code Generation” on page 6-7 for more information. Do not reference fields dynamically You cannot reference fields in a structure by using dynamic names, which express the field as a variable expression that MATLAB evaluates at run time (see “Dynamic Field Names” in the MATLAB Getting Started Guide).

6-11

6

Code Generation for MATLAB? Structures

Assigning Values to Structures and Fields
Use these guidelines when assigning values to a structure, substructure, or field for code generation: Field properties must be consistent across structure-to-structure assignments If: Assigning one structure to another structure. Assigning one structure to a substructure of a different structure and vice versa. Assigning an element of one structure to an element of another structure. Then: Define each structure with the same number, type, and size of fields. Define the structure with the same number, type, and size of fields as the substructure. The elements must have the same type and size.

Do not use field values as constants The values stored in the fields of a structure are not treated as constant values in generated code. Therefore, you cannot use field values to set the size or class of other data. For example, the following code generates a compiler error:
... Y.a = 3; X = zeros(Y.a); % Generates an error

In this example, even though you set field a of structure Y to the value 3, Y.a is not a constant in generated code and, therefore, it is not a valid argument to pass to the function zeros. Do not assign mxArrays to structures You cannot assign mxArrays to structure elements; convert mxArrays to known types before code generation (see “Working with mxArrays” on page 11-16).

6-12

Passing Large Structures as Input Parameters

Passing Large Structures as Input Parameters
If you generate a MEX function for a MATLAB function that takes a large structure as an input parameter, for example, a structure containing fields that are matrices, the MEX function might fail to load. This load failure occurs because, when you generate a MEX function from a MATLAB function that has input parameters, the code generation software allocates memory for these input parameters on the stack. To avoid this issue, pass the structure by reference to the MATLAB function. For example, if the original function signature is:
y = foo(a, S)

where S is the structure input, rewrite the function to:
[y, S] = foo(a, S)

6-13

6

Code Generation for MATLAB? Structures

6-14

7
Code Generation for Enumerated Data
? “How Working with Enumerated Data Is Different for Code Generation” on page 7-2 ? “Enumerated Types Supported for Code Generation” on page 7-3 ? “When to Use Enumerated Data for Code Generation” on page 7-6 ? “Workflows for Using Enumerated Data for Code Generation” on page 7-7 ? “How to Define Enumerated Data for Code Generation” on page 7-9 ? “How to Instantiate Enumerated Types for Code Generation” on page 7-11 ? “How to Generate Code for Enumerated Data” on page 7-12 ? “Defining and Using Enumerated Types for Code Generation” on page 7-13 ? “Operations on Enumerated Data Allowed for Code Generation” on page 7-15 ? “Using Enumerated Data in Control Flow Statements” on page 7-18 ? “Restrictions on Use of Enumerated Data in for-Loops” on page 7-24 ? “Toolbox Functions That Support Enumerated Types for Code Generation” on page 7-25

7

Code Generation for Enumerated Data

How Working with Enumerated Data Is Different for Code Generation
To generate efficient standalone code for enumerated data, you must define and use enumerated types differently than you normally would when running your code in the MATLAB environment: What’s Different Supports integer-based enumerated types only Name of each enumerated data type must be unique Each enumerated data type must be defined in a separate file on the MATLAB path Restricted set of operations More Information “Enumerated Types Supported for Code Generation” on page 7-3 “Naming Enumerated Types for Code Generation” on page 7-10 “How to Define Enumerated Data for Code Generation” on page 7-9 and “How to Generate Code for Enumerated Data” on page 7-12 “Operations on Enumerated Data Allowed for Code Generation” on page 7-15 “Restrictions on Use of Enumerated Data in for-Loops” on page 7-24

Restricted use in for-loops

See Also
? “How to Define Enumerated Data for Code Generation” on page 7-9 ? “Defining and Organizing Classes” in the MATLAB Object-Oriented Programming documentation for more information about defining MATLAB classes ? “Enumerations and Modeling” for more information about enumerated types based on Simulink.IntEnumType

7-2

Enumerated Types Supported for Code Generation

Enumerated Types Supported for Code Generation
In this section... “Enumerated Type Based on int32” on page 7-3 “Enumerated Type Based on Simulink.IntEnumType” on page 7-4

Enumerated Type Based on int32
This enumerated data type is based on the built-in type int32. Use this enumerated type when generating code from MATLAB algorithms.

Syntax
classdef(Enumeration) type_name < int32

Example
classdef(Enumeration) PrimaryColors < int32 enumeration Red(1), Blue(2), Yellow(4) end end

In this example, the statement classdef(Enumeration) PrimaryColors < int32 means that the enumerated type PrimaryColors is based on the built-in type int32. As such, PrimaryColors inherits the characteristics of the int32 type, as well as defining its own unique characteristics. For example, PrimaryColors is restricted to three enumerated values: Enumerated Value
Red(1) Blue(2) Yellow(4)

Enumerated Name
Red Blue Yellow

Underlying Numeric Value 1 2 4

7-3

7

Code Generation for Enumerated Data

How to Use
Define enumerated data in MATLAB code and compile the source file. For example, to generate C/C++ code from your MATLAB source, you can use codegen, as described in “Workflow for Generating Code for Enumerated Data from MATLAB Algorithms” on page 7-7. Note codegen requires a MATLAB Coder license.

Enumerated Type Based on Simulink.IntEnumType
This enumerated data type is based on the built-in type Simulink.IntEnumType, which is available with a Simulink license. Use this enumerated type when exchanging enumerated data with Simulink blocks and Stateflow charts.

Syntax
classdef(Enumeration) type_name < Simulink.IntEnumType

Example
classdef(Enumeration) myMode < Simulink.IntEnumType enumeration OFF(0) ON(1) end end

How to Use
Here are the basic guidelines for using enumerated data based on Simulink.IntEnumType:

7-4

Enumerated Types Supported for Code Generation

Application When exchanging enumerated data with Simulink blocks When exchanging enumerated data with Stateflow charts For more information, see:

What to Do Define enumerated data in MATLAB Function blocks in Simulink models. Requires Simulink software. Define enumerated data in MATLAB functions in Stateflow charts. Requires Simulink and Stateflow software.

? “Using Enumerated Data in MATLAB Function Blocks” in the Simulink documentation ? “Using Enumerated Data in Stateflow Charts” in the Stateflow documentation

7-5

7

Code Generation for Enumerated Data

When to Use Enumerated Data for Code Generation
You can use enumerated types to represent program states and to control program logic, especially when you need to restrict data to a finite set of values and refer to these values by name. Even though you can sometimes achieve these goals by using integers or strings, enumerated types offer the following advantages: ? Provide more readable code than integers ? Allow more robust error checking than integers or strings For example, if you mistype the name of an element in the enumerated type, you get a compile-time error that the element does not belong to the set of allowable values. ? Produce more efficient code than strings For example, comparisons of enumerated values execute faster than comparisons of strings.

7-6

Workflows for Using Enumerated Data for Code Generation

Workflows for Using Enumerated Data for Code Generation
In this section... “Workflow for Generating Code for Enumerated Data from MATLAB Algorithms” on page 7-7 “Workflow for Generating Code for Enumerated Data from MATLAB Function Blocks” on page 7-8

Workflow for Generating Code for Enumerated Data from MATLAB Algorithms
Step
1

Action Define an enumerated data type that inherits from int32. Instantiate the enumerated type in your MATLAB algorithm. Compile the function with codegen.

How? See “How to Define Enumerated Data for Code Generation” on page 7-9. See “How to Instantiate Enumerated Types for Code Generation” on page 7-11. See “How to Generate Code for Enumerated Data” on page 7-12.

2

3

This workflow requires a MATLAB Coder license.

7-7

7

Code Generation for Enumerated Data

Workflow for Generating Code for Enumerated Data from MATLAB Function Blocks
Step
1

Action Define an enumerated data type that inherits from Simulink.IntEnumType. Add the enumerated data to your MATLAB Function block.

How? See “How to Define Enumerated Data Types for MATLAB Function Blocks” in the Simulink documentation. See “How to Add Enumerated Data to MATLAB Function Blocks” in the Simulink documentation. See “How to Instantiate Enumerated Data in MATLAB Function Blocks” in the Simulink documentation. See “Enumerations” in the Simulink Coder documentation.

2

3

Instantiate the enumerated type in your MATLAB Function block.

Simulate and/or generate code.
4

This workflow requires the following licenses: ? Simulink (for simulation) ? MATLAB Coder and Simulink Coder (for code generation)

7-8

How to Define Enumerated Data for Code Generation

How to Define Enumerated Data for Code Generation
Follow these to define enumerated data for code generation from MATLAB algorithms:
1 Create a class definition file.

In the MATLAB Command Window, select File > New > Class.
2 Enter the class definition as follows:

classdef(Enumeration) EnumTypeName < int32

For example, the following code defines an enumerated type called sysMode:
classdef(Enumeration) sysMode < int32 ... end EnumTypeName is a case-sensitive string that must be unique among data

type names and workspace variable names. It must inherit from the built-in type int32.
3 Define enumerated values in an enumeration section as follows:

classdef(Enumeration) EnumTypeName < int32 enumeration
EnumName(N)

... end end

For example, the following code defines a set of two values for enumerated type sysMode:
classdef(Enumeration) sysMode < int32 enumeration OFF(0) ON(1) end end

7-9

7

Code Generation for Enumerated Data

An enumerated type can define any number of values. Each enumerated value consists of a string EnumName and an underlying integer N. Each EnumName must be unique within its type, but can also appear in other enumerated types. The underlying integers need not be either consecutive or ordered, nor must they be unique within the type or across types.
4 Save the file on the MATLAB path.

The name of the file must match the name of the enumerated data type. The match is case sensitive. To add a folder to the MATLAB search path, type addpath pathname at the MATLAB command prompt. For more information, see “Using the MATLAB Search Path”, addpath, and savepath in the MATLAB documentation. For examples of enumerated data type definitions, see “Class Definition: sysMode” on page 7-13 and “Class Definition: LEDcolor” on page 7-14.

Naming Enumerated Types for Code Generation
You must use a unique name for each enumerated data type. The name of an enumerated data type cannot match the name of a toolbox function supported for code generation, or another data type or a variable in the MATLAB base workspace. Otherwise, a name conflict occurs. For example, you cannot name an enumerated data type mode because MATLAB for code generation provides a toolbox function of the same name. For a list of toolbox functions supported for code generation, see Chapter 2, “Functions Supported for Code Generation”.

7-10

How to Instantiate Enumerated Types for Code Generation

How to Instantiate Enumerated Types for Code Generation
To instantiate an enumera

相关文章:
Simulink 3D Animation User's Guide R2011B.pdf
Simulink 3D Animation User's Guide R2011B_机械/仪表_工程科技_专业资料。Simulink...From the MATLAB software, you can set positions and properties of VRML ...
基于MatlabR2011b的卫星轨道计算.pdf
Matlab R2011b 的卫星轨道计算牛晓楠, 蒋丹丹, 霍红娟(中国矿业大
matlab-coder-code-generation-quick-start-guide-r201....pdf
Feedback/Questions: email matlab-coder-expert@mathworks.com Generating C code with MATLAB Coder: a Quick Start Guide (R2013a) ? What’s the difference...
关于64位win7下安装matlab R2011b的一些心得.doc
关于64位win7下安装matlab R2011b的一些心得_理学_高等教育_教育专区。关于64位win7下安装matlab R2011b的一些心得 QQ763871679 整理 关于 64 位 win7 下安装 ...
vs2010和Matlab R2011b 混合编程---使用COM组件.doc
vs2010 和 Matlab R2011b 混合编程---使用 COM 组件 (VS2010+Matlab7.11) COM 是 component object module 的简称,它是一种通用的对象接 口,任何语言只要按...
MATLAB.R2011b详细安装教程(含matlab下载安装、虚拟光....pdf
MATLAB.R2011b详细安装教程(含matlab下载安装、虚拟光驱下载安装、Visual C++安装)_电子/电路_工程科技_专业资料。MATLAB.R2011b 安装教程 (含 matlab 下载安装+...
Matlab2011b安装步骤详解_图文.doc
Matlab2011b安装步骤详解_理学_高等教育_教育专区。matlab2011b迅雷下载地址: ed2k://|file|Mathworks.Matlab.R2011b.ISO-TBE.iso|5852555264|fe70a7cdd91bbcb179...
matlabR2011b与 vc++6.0混合编程.txt
matlabR2011b与 vc++6.0混合编程_计算机软件及应用_IT/计算
matlab 2011b 下载地址、安装说明、新功能介绍。.doc
Matlab 2011b 下载地址 [矩阵实验室].TLF-SOFT-Mathworks.Matlab.R2011b.ISO-TBE.iso ed2k://|file|%5B%E7%9F%A9%E9%98%B5%E5%AE%9E%E9%AA%8C%E5%...
MATLAB+2011b+详细安装过程.pdf
MATLAB 2011b 详细安装过程 MATLAB 2011b 详细安装过程与以前版本类似,MATLAB 2011b 专业版对安装 Windows 操作系统的计算机的基本配置要求是: 操作系统 Win 7 ...
MATLAB Link for Code Composer Studio Development To....pdf
MATLAB Link for Code Composer Studio Development Tools Users Guide_能源/...Code Generation from M... 301页 免费 MATLAB Link for CCS De... 3...
Wavelet Toolbox Release Notes.pdf
. Scalograms for Continuous Wavelet Transforms . ...Wavelet Toolbox graphical user interface wavemenu....7 R2011b MATLAB Code Generation Support for ...
Polyspace UML Link RH User's Guide_图文.pdf
Polyspace UML Link RH User's Guide_计算机软件及...\Polyspace\PolyspaceForCandCPP_R2011b\Verifier\...MATLAB Link for Code C... 36页 2下载券 Holtek...
MATLAB Report Generator Release Notes.pdf
in the MATLAB Report Generator Users Guide. 15...21 R2010b Enhanced Error Handling Code for ...or from snapshot components such as the Axes Snap...
Matlab - Optimisation Toolbox - User's Guide.pdf
Matlab - Optimisation Toolbox - User's Guide_数学...x ≤ b, Aeq ? x = beq, l ≤ x ≤ u T...This example uses bananaobj from the preceding ...
Polyspace Model Link Products User's Guide_图文.pdf
Model Link Products Users Guide R2012b How to...Run Verification from the Command Window . . . ...Simulink model and generate code: 1 Open MATLAB?...
Matlab R2011a 安装图解.pdf
Matlab R2011a 安装图解_IT/计算机_专业资料。MATLAB 2011a 详细安装过程本人去年在这里发表了安装 MATLAB 2010b 的帖子(见 http://www.ilovematlab.cn/view...
STK10与Matlab互联(STK10 破解).pdf
d:\Program?Files?(x86)\MATLAB\R2011b\bin\win...s guide provi ides instructions for sett ting ...MATLAB user area, the location of the AGI MEX ...
AdderSubtra....pdf
AdderSubtr...MATLAB and Simulink are registered trademarks of ...See the System Generator for DSP User Guide for...
北航Matlab教程(R2011a)习题4解答.doc
A=magic(8) B=orth(A) rref(A) rref(B) 8. 已知由 MATLAB 指令创建的...s')]),disp([cr,poly2str(r,'s')]) qp2=conv(q,DX), pp1=qp2+r...