معرفی چند منبع در زمینه آموزش برنامه نویسی MATLABیا متلب کتاب های به زبان فارسی کتاب های به زبان انگلیسی عنوانMatlab, Third Edition: A Practical Introduction to : Programming and Problem Solving ترجمه عنوان :متلب :مقدمه ای عملی بر برنامه نويسی و حل مساله ،چاپ سوم مولفینStormy Attaway : عنوان :اصول و مبانی متلب برای علوم مهندسی مولفین :برايان هان ،دانیل تی ،والنتین مترجمین :رامین موالنا پور ،سارا موالناپور ،نینا اسدی پور انتشارات :سها دانش سال چاپ2013 : لینک دسترسی :لینک انتشاراتButterworth-Heinemann : لینک دسترسی :لینک عنوانMATLAB For Dummies : عنوان :کاربرد MATLABدر علوم مهندسی ترجمه عنوان :تلب به زبان ساده مولفین :حیدرعلی شايانفر ،حسین شايقی مولفینJim Sizemore, John Paul Mueller : انتشارات :ياوريان سال چاپ2014 : لینک دسترسی :لینک انتشاراتFor Dummies : لینک دسترسی :لینک عنوانEssential MATLAB for Engineers and Scientists : عنوان :برنامه نويسی MATLABبرای مهندسان ترجمه عنوان :آنچه بايد مهندسین و دانشمندان از متلب بدانند مولفین :محمود کشاورز مهر ،بهزاد عبدی مولفینBrian Hahn, Daniel Valentine: انتشارات :نوپردازان سال چاپ2013 : لینک دسترسی :لینک انتشاراتAcademic Press : لینک دسترسی :لینک عنوانMATLAB: An Introduction with Applications : عنوان :آموزش کاربردی مباحث پیشرفته با MATLAB ترجمه عنوان :مقدمه ای بر متلب و کاربردهای آن مولفین :نیما جمشیدی ،علی ابويی مهريزی ،رسول مواليی مولفAmos Gilat : انتشارات :عابد سال چاپ2014 : لینک دسترسی :لینک انتشاراتWiley : لینک دسترسی :لینک عنوانMATLAB For Beginners: A Gentle Approach: عنوان :کاملترين مرجع آموزشی و کاربردی MATLAB ترجمه عنوان :متلب برای افراد مبتدی با يک رويکرد تدريجی مولفین :علی اکبر علمداری ،نسرين علمداری مولفPeter I. Kattan: انتشارات :نگارنده دانش سال چاپ2008 : انتشاراتCreateSpace Independent Publishing Platform : لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB for Engineers : عنوان :برنامه نويسی MATLABبرای مهندسین ترجمه عنوان :متلب برای مهندسین مولف :استفن چاپمن مولفHolly Moore : مترجم :سعدان زکائی سال چاپ2011 : انتشارات :دانشگاه صنعتی خواجه نصیرالدين طوسی انتشاراتPrentice Hall : لینک دسترسی :لینک لینک دسترسی :لینک عنوانMastering MATLAB : عنوان :آموزش گام به گام محاسبات عددی با متلب ترجمه عنوان :تسلط بر متلب مولفینDuane C. Hanselman, Bruce L. Littlefield : سال چاپ2011 : مولف :کلیو مولر مترجم :رسول نصیری انتشارات :نشر گستر انتشاراتPrentice Hall : لینک دسترسی :لینک لینک دسترسی :لینک ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان منابع آموزشی آنالین عنوان :مجموعه فرادرسهای برنامهنويسی متلب مدرس :دکتر سید مصطفی کالمی هريس مدت زمان ۹ :ساعت و ۳دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوان :مجموعه فرادرسهای متلب برای علوم و مهندسی مدرس :دکتر سید مصطفی کالمی هريس مدت زمان 14 :ساعت و 2۲دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوان :مجموعه فرادرسهای برنامه نويسی متلب پیشرفته مدرس :دکتر سید مصطفی کالمی هريس مدت زمان ۲ :ساعت و 12دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوانIntroduction to Programming with MATLAB : ترجمه عنوان :آشنايی با برنامهنويسی متلب مدرسینAkos Ledeczi, Michael Fitzpatrick, Robert Tairas : زبان :انگلیسی ارائه دهندهVanderbilt University : لینک دسترسی :لینک عنوانIntroduction to MATLAB : ترجمه عنوان :مقدمهای بر متلب مدرسDanilo Šćepanović : زبان :انگلیسی ارائه دهندهMIT OCW : لینک دسترسی :لینک عنوانUp and Running with MATLAB : ترجمه عنوان :شروع سريع کار با متلب مدرسPatrick Royal : زبان :انگلیسی ارائه دهندهlynda.com : لینک دسترسی :لینک عنوانModelling and Simulation using MATLAB : ترجمه عنوان :مدلسازی و شبیهسازی با استفاده از متلب مدرسین Prof. Dr.-Ing. Georg Fries :و دیگران زبان :انگلیسی ارائه دهندهiversity.org : لینک دسترسی :لینک ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB® Coder™ User's Guide R2014b www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان How to Contact MathWorks Latest news: www.mathworks.com Sales and services: www.mathworks.com/sales_and_services User community: www.mathworks.com/matlabcentral Technical support: www.mathworks.com/support/contact_us Phone: 508-647-7000 The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098 MATLAB® Coder™ User's Guide © COPYRIGHT 2011–2014 by The MathWorks, Inc. The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc. FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to The MathWorks, Inc. Trademarks MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders. Patents MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for more information. Revision History April 2011 September 2011 March 2012 September 2012 March 2013 September 2013 March 2014 October 2014 Online only Online only Online only Online only Online only Online only Online only Online only New for Version 2 (R2011a) Revised for Version 2.1 (Release 2011b) Revised for Version 2.2 (Release 2012a) Revised for Version 2.3 (Release 2012b) Revised for Version 2.4 (Release 2013a) Revised for Version 2.5 (Release 2013b) Revised for Version 2.6 (Release 2014a) Revised for Version 2.7 (Release 2014b) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Check Bug Reports for Issues and Fixes Software is inherently complex and is not free of errors. The output of a code generator might contain bugs, some of which are not detected by a compiler. MathWorks reports critical known bugs brought to its attention on its Bug Report system at www.mathworks.com/support/bugreports/. Use the Saved Searches and Watched Bugs tool with the search phrase "Incorrect Code Generation" to obtain a report of known bugs that produce code that might compile and execute, but still produce wrong answers. The bug reports are an integral part of the documentation for each release. Examine periodically all bug reports for a release, as such reports may identify inconsistencies between the actual behavior of a release you are using and the behavior described in this documentation. In addition to reviewing bug reports, you should implement a verification and validation strategy to identify potential bugs in your design, code, and tools. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Contents About MATLAB Coder 1 2 MATLAB Coder Product Description . . . . . . . . . . . . . . . . . . . Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1-2 Product Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . When to Use MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . Code Generation for Embedded Software Applications . . . . . Code Generation for Fixed-Point Algorithms . . . . . . . . . . . . . 1-3 1-3 1-3 1-3 Code Generation Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 1-5 Design Considerations for C/C++ Code Generation When to Generate Code from MATLAB Algorithms . . . . . . . When Not to Generate Code from MATLAB Algorithms . . . . 2-2 2-2 Which Code Generation Feature to Use . . . . . . . . . . . . . . . . . 2-4 Prerequisites for C/C++ Code Generation from MATLAB . . . 2-5 MATLAB Code Design Considerations for Code Generation See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 2-7 Differences in Behavior After Compiling MATLAB Code . . . Why Are There Differences? . . . . . . . . . . . . . . . . . . . . . . . . . Character Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Order of Evaluation in Expressions . . . . . . . . . . . . . . . . . . . . Termination Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 2-8 2-8 2-8 2-9 v www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Size of Variable-Size N-D Arrays . . . . . . . . . . . . . . . . . . . . . Size of Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Floating-Point Numerical Results . . . . . . . . . . . . . . . . . . . . NaN and Infinity Patterns . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation Target . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Class Initial Values . . . . . . . . . . . . . . . . . . . . . . . Variable-Size Support for Code Generation . . . . . . . . . . . . . MATLAB Language Features Supported for C/C++ Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Language Features Not Supported for C/C++ Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2-12 3-2 Functions, Classes, and System Objects Supported for Code Generation Functions and Objects Supported for C and C++ Code Generation — Alphabetical List . . . . . . . . . . . . . . . . . . . . . . Functions and Objects Supported for C and C++ Code Generation — Category List . . . . . . . . . . . . . . . . . . . . . . . Aerospace Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Arithmetic Operations in MATLAB . . . . . . . . . . . . . . . . . . Bit-Wise Operations MATLAB . . . . . . . . . . . . . . . . . . . . . Casting in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Communications System Toolbox . . . . . . . . . . . . . . . . . . . Complex Numbers in MATLAB . . . . . . . . . . . . . . . . . . . . . Computer Vision System Toolbox . . . . . . . . . . . . . . . . . . . Control Flow in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . Data and File Management in MATLAB . . . . . . . . . . . . . . Data Types in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . vi 2-12 System Objects Supported for Code Generation Code Generation for System Objects . . . . . . . . . . . . . . . . . . . 4 2-9 2-9 2-10 2-10 2-11 2-11 2-11 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-2 4-134 4-136 4-136 4-137 4-138 4-138 4-144 4-144 4-153 4-154 4-157 Desktop Environment in MATLAB . . . . . . . . . . . . . . . . . . Discrete Math in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . DSP System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Error Handling in MATLAB . . . . . . . . . . . . . . . . . . . . . . . Exponents in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . Filtering and Convolution in MATLAB . . . . . . . . . . . . . . . Fixed-Point Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HDL Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Histograms in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . Image Acquisition Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . Image Processing in MATLAB . . . . . . . . . . . . . . . . . . . . . . Image Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . Input and Output Arguments in MATLAB . . . . . . . . . . . . Interpolation and Computational Geometry in MATLAB . . Linear Algebra in MATLAB . . . . . . . . . . . . . . . . . . . . . . . Logical and Bit-Wise Operations in MATLAB . . . . . . . . . . MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Matrices and Arrays in MATLAB . . . . . . . . . . . . . . . . . . . Neural Network Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . Nonlinear Numerical Methods in MATLAB . . . . . . . . . . . . Numerical Integration and Differentiation in MATLAB . . . Optimization Functions in MATLAB . . . . . . . . . . . . . . . . . Phased Array System Toolbox . . . . . . . . . . . . . . . . . . . . . . Polynomials in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . Programming Utilities in MATLAB . . . . . . . . . . . . . . . . . . Relational Operators in MATLAB . . . . . . . . . . . . . . . . . . . Rounding and Remainder Functions in MATLAB . . . . . . . Set Operations in MATLAB . . . . . . . . . . . . . . . . . . . . . . . Signal Processing in MATLAB . . . . . . . . . . . . . . . . . . . . . Signal Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . Special Values in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . Specialized Math in MATLAB . . . . . . . . . . . . . . . . . . . . . . Statistics in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . Statistics Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . String Functions in MATLAB . . . . . . . . . . . . . . . . . . . . . . Structures in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . Trigonometry in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 4-158 4-158 4-159 4-166 4-167 4-167 4-168 4-178 4-178 4-178 4-178 4-179 4-186 4-187 4-190 4-191 4-191 4-192 4-199 4-199 4-199 4-200 4-201 4-209 4-209 4-209 4-210 4-210 4-215 4-216 4-221 4-221 4-222 4-222 4-231 4-233 4-233 vii www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 6 Defining MATLAB Variables for C/C++ Code Generation Variables Definition for Code Generation . . . . . . . . . . . . . . . 5-2 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 . . . . . . . 5-3 5-3 5-5 5-5 5-6 Eliminate Redundant Copies of Variables in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . When Redundant Copies Occur . . . . . . . . . . . . . . . . . . . . . . . How to Eliminate Redundant Copies by Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . . 5-7 5-8 Reassignment of Variable Properties . . . . . . . . . . . . . . . . . . . 5-9 Define and Initialize Persistent Variables . . . . . . . . . . . . . . 5-10 Reuse 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 . . . . . . . . . . . . . . . . . . . . . . . 5-11 Avoid Overflows in for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . 5-15 Supported Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17 5-11 5-11 5-14 Defining Data for Code Generation Data Definition for Code Generation . . . . . . . . . . . . . . . . . . . viii 5-7 5-7 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-2 7 Code Generation for Complex Data . . . . . . . . . . . . . . . . . . . . Restrictions When Defining Complex Variables . . . . . . . . . . . Expressions With Complex Operands Yield Complex Results . 6-4 6-4 6-4 Code Generation for Characters . . . . . . . . . . . . . . . . . . . . . . . 6-6 Array Size Restrictions for Code Generation . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7 6-7 Code Generation for Variable-Size Data What Is Variable-Size Data? . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2 Variable-Size Data Definition for Code Generation . . . . . . . 7-3 Bounded Versus Unbounded Variable-Size Data . . . . . . . . . . 7-4 Control Memory Allocation of Variable-Size Data . . . . . . . . . 7-5 Specify Variable-Size Data Without Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Fixing Upper Bounds Errors . . . . . . . . . . . . . . . . . . . . . . . . . Specifying Upper Bounds for Variable-Size Data . . . . . . . . . . 7-6 7-6 7-6 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 . . . . . . . . . . . . 7-9 7-9 7-10 7-10 Define Variable-Size Data for Code Generation . . . . . . . . . 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 . 7-11 7-11 7-11 7-12 7-13 C Code Interface for Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . C Code Interface for Statically Allocated Arrays . . . . . . . . . C Code Interface for Dynamically Allocated Arrays . . . . . . . Utility Functions for Creating emxArray Data Structures . . 7-17 7-17 7-18 7-19 ix www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Diagnose and Fix Variable-Size Data Errors . . . . . . . . . . . . Diagnosing and Fixing Size Mismatch Errors . . . . . . . . . . . Diagnosing and Fixing Errors in Detecting Upper Bounds . . Incompatibilities with MATLAB in Variable-Size Support for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Incompatibility with MATLAB for Scalar Expansion . . . . . . Incompatibility with MATLAB in Determining Size of VariableSize N-D Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Incompatibility with MATLAB in Determining Size of Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Incompatibility with MATLAB in Determining Class of Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Incompatibility with MATLAB in Vector-Vector Indexing . . Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . Incompatibility with MATLAB in Concatenating Variable-Size Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dynamic Memory Allocation Not Supported for MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Variable-Sizing Restrictions for Code Generation of Toolbox Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Common Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Toolbox Functions with Variable Sizing Restrictions . . . . . . 8 x 7-21 7-21 7-23 7-25 7-25 7-27 7-28 7-29 7-30 7-30 7-31 7-32 7-33 7-33 7-34 Code Generation for MATLAB Structures Structure Definition for Code Generation . . . . . . . . . . . . . . . 8-2 Structure Operations Allowed for Code Generation . . . . . . . 8-3 Define Scalar Structures for Code Generation . . . . . . . . . . . Restriction 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 . . . . . . . . . 8-4 8-4 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-4 8-4 8-5 9 Define 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 . . . . . . 8-7 8-7 Make Structures Persistent . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9 Index Substructures and Fields . . . . . . . . . . . . . . . . . . . . . . . 8-10 Assign Values to Structures and Fields . . . . . . . . . . . . . . . . 8-12 Pass Structure Arguments by Reference or by Value . . . . . Specify Pass by Reference or by Value Using a Project . . . . Specify Pass by Reference or by Value Using the CommandLine Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pass Input Structure Argument by Reference . . . . . . . . . . . Pass Input Structure Argument by Value . . . . . . . . . . . . . . Pass Output Structure Argument by Reference . . . . . . . . . . Pass Output Structure Argument by Value . . . . . . . . . . . . . Pass Input and Output Structure Argument by Reference . . 8-14 8-14 8-7 8-8 8-15 8-15 8-16 8-16 8-17 8-18 Code Generation for Enumerated Data Enumerated Data Definition for Code Generation . . . . . . . . 9-2 Enumerated Types Supported for Code Generation . . . . . . . Enumeration Class Base Types for Code Generation . . . . . . . C Code Representation for Base Type int32 . . . . . . . . . . . . C Code Representation for Base Type Other Than int32 . . . 9-3 9-3 9-4 9-4 When to Use Enumerated Data for Code Generation . . . . . . 9-6 Generate Code for Enumerated Data from MATLAB Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7 9-7 Define Enumerated Data for Code Generation . . . . . . . . . . . Naming Enumerated Types for Code Generation . . . . . . . . . . 9-8 9-9 xi www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Operations on Enumerated Data for Code Generation . . . . Assignment Operator, = . . . . . . . . . . . . . . . . . . . . . . . . . . . Relational Operators, < > <= >= == ~= . . . . . . . . . . . . . . . . Cast Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Indexing Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Control Flow Statements: if, switch, while . . . . . . . . . . . . . 9-10 9-10 9-10 9-10 9-11 9-11 Include Enumerated Data in Control Flow Statements . . . if Statement with Enumerated Data Types . . . . . . . . . . . . switch Statement with Enumerated Data Types . . . . . . . . while Statement with Enumerated Data Types . . . . . . . . . 9-13 9-13 9-14 9-16 Customize Enumerated Types for Code Generation . . . . . . Customizing Enumerated Types . . . . . . . . . . . . . . . . . . . . . Specify a Default Enumerated Value . . . . . . . . . . . . . . . . . . Specify a Header File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-19 9-19 9-20 9-21 Use Enumerated Types in LED Control Function . . . . . . . . 9-23 Control Names of Enumerated Type Values in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-26 Change and Reload Enumerated Data Types . . . . . . . . . . . . 9-29 Restrictions on Use of Enumerated Data in for-Loops . . . . 9-30 Toolbox Functions That Support Enumerated Types for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-31 10 xii Code Generation for MATLAB Classes MATLAB Classes Definition for Code Generation . . . . . . . . Language Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation Features Not Compatible with Classes . . . Defining Class Properties for Code Generation . . . . . . . . . . Calls to Base Class Constructor . . . . . . . . . . . . . . . . . . . . . Inheritance from Built-In MATLAB Classes Not Supported . 10-2 10-2 10-3 10-4 10-5 10-6 Classes That Support Code Generation . . . . . . . . . . . . . . . . 10-7 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11 12 Generate Code for MATLAB Value Classes . . . . . . . . . . . . . 10-8 Generate Code for MATLAB Handle Classes and System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-13 MATLAB Classes in Code Generation Reports . . . . . . . . . . What Reports Tell You About Classes . . . . . . . . . . . . . . . . How Classes Appear in Code Generation Reports . . . . . . . How to Generate a Code Generation Report . . . . . . . . . . . 10-15 10-15 10-15 10-17 Troubleshooting Issues with MATLAB Classes . . . . . . . . . Class class does not have a property with name name . . . . 10-18 10-18 Code Generation for Function Handles Function Handle Definition for Code Generation . . . . . . . . 11-2 Define and Pass Function Handles for Code Generation . . 11-3 Function Handle Limitations for Code Generation . . . . . . . 11-5 Defining Functions for Code Generation Specify Variable Numbers of Arguments . . . . . . . . . . . . . . . 12-2 Supported Index Expressions . . . . . . . . . . . . . . . . . . . . . . . . 12-3 Apply Operations to a Variable Number of Arguments . . . . When to Force Loop Unrolling . . . . . . . . . . . . . . . . . . . . . . Using Variable Numbers of Arguments in a for-Loop . . . . . . 12-4 12-4 12-5 Implement Wrapper Functions . . . . . . . . . . . . . . . . . . . . . . . 12-6 Passing Variable Numbers of Arguments from One Function to Another . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6 xiii www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Pass Property/Value Pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7 Variable Length Argument Lists for Code Generation . . . . 12-9 Calling Functions for Code Generation Resolution of Function Calls for Code Generation . . . . . . . Key Points About Resolving Function Calls . . . . . . . . . . . . . Compile Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . When to Use the Code Generation Path . . . . . . . . . . . . . . . 13-2 13-4 13-4 13-5 Resolution of File Types on Code Generation Path . . . . . . . 13-6 Compilation Directive %#codegen . . . . . . . . . . . . . . . . . . . . . 13-8 Call Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-9 Call Supported Toolbox Functions . . . . . . . . . . . . . . . . . . . 13-10 Call 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 . . . . . . . . . . . . . . . . . . . . . . 13-11 13-12 13-16 Fixed-Point Conversion 14 xiv 13-16 13-17 13-19 13-19 Convert MATLAB Code to Fixed-Point C Code . . . . . . . . . . 14-3 Propose Fixed-Point Data Types Based on Simulation Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-4 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Propose Fixed-Point Data Types Based on Derived Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-18 Type Proposal Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-34 Detect Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-38 Replace the exp Function with a Lookup Table . . . . . . . . 14-45 Replace a Custom Function with a Lookup Table . . . . . . . 14-51 Enable Plotting Using the Simulation Data Inspector . . . 14-58 Log Data for Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-59 View and Modify Variable Information . . . . . . . . . . . . . . . View Variable Information . . . . . . . . . . . . . . . . . . . . . . . . Modify Variable Information . . . . . . . . . . . . . . . . . . . . . . . Revert Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Promote Sim Min and Sim Max Values . . . . . . . . . . . . . . . 14-62 14-62 14-62 14-64 14-65 Build Instrumented MEX Function . . . . . . . . . . . . . . . . . . . 14-66 Propose Fixed-Point Data Types . . . . . . . . . . . . . . . . . . . . . 14-67 Apply Fixed-Point Data Types . . . . . . . . . . . . . . . . . . . . . . . 14-77 Modify Data Type Proposal Settings . . . . . . . . . . . . . . . . . . 14-82 Modify Instrumentation Report Settings . . . . . . . . . . . . . . 14-85 Automated Fixed-Point Conversion . . . . . . . . . . . . . . . . . . License Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . Automated Fixed-Point Conversion Capabilities . . . . . . . . Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Proposing Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . Locking Proposed Data Types . . . . . . . . . . . . . . . . . . . . . . Viewing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viewing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Function Replacements . . . . . . . . . . . . . . . . . . . . . . . . . . Validating Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Testing Numerics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-86 14-86 14-86 14-88 14-91 14-93 14-93 14-94 14-100 14-102 14-103 14-103 xv www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Detecting Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi 14-104 Instrumented MEX Functions . . . . . . . . . . . . . . . . . . . . . . Generating Instrumented MEX Functions . . . . . . . . . . . . Merging Instrumentation Results . . . . . . . . . . . . . . . . . . Clearing Instrumentation Results . . . . . . . . . . . . . . . . . . Redirecting Entry-Point Calls to MEX Function . . . . . . . Proposing Fraction Lengths . . . . . . . . . . . . . . . . . . . . . . . Proposing Word Lengths . . . . . . . . . . . . . . . . . . . . . . . . . 14-105 14-105 14-105 14-106 14-106 14-106 14-106 Convert Fixed-Point Conversion Project to MATLAB Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-107 Generated Fixed-Point Code . . . . . . . . . . . . . . . . . . . . . . . Location of Generated Fixed-Point Files . . . . . . . . . . . . . Minimizing fi-casts to Improve Code Readability . . . . . . Avoiding Overflows in the Generated Fixed-Point Code . . Controlling Bit Growth . . . . . . . . . . . . . . . . . . . . . . . . . . Avoiding Loss of Range or Precision . . . . . . . . . . . . . . . . Handling Non-Constant mpower Exponents . . . . . . . . . . 14-110 14-110 14-111 14-111 14-112 14-112 14-114 Fixed-Point Code for MATLAB Classes . . . . . . . . . . . . . . . Automated Conversion Support for MATLAB Classes . . . Unsupported Constructs . . . . . . . . . . . . . . . . . . . . . . . . . Coding Style Best Practices . . . . . . . . . . . . . . . . . . . . . . . 14-116 14-116 14-116 14-117 Automated Fixed-Point Conversion Best Practices . . . . . Create a Test File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Prepare Your Algorithm for Code Acceleration or Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Check for Fixed-Point Support for Functions Used in Your Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Manage Data Types and Control Bit Growth . . . . . . . . . . Convert to Fixed Point . . . . . . . . . . . . . . . . . . . . . . . . . . Use the Histogram to Fine-Tune Data Type Settings . . . . Optimize Your Algorithm . . . . . . . . . . . . . . . . . . . . . . . . Avoid Explicit Double and Single Casts . . . . . . . . . . . . . . 14-119 14-119 14-120 14-121 14-121 14-122 14-122 14-124 14-126 Replacing Functions Using Lookup Table Approximations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-128 MATLAB Language Features Supported for Automated Fixed-Point Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 14-129 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Inspecting Data Using the Simulation Data Inspector . . What Is the Simulation Data Inspector? . . . . . . . . . . . . . Import Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . Export Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . Group Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Run Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Create Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comparison Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . Enabling Plotting Using the Simulation Data Inspector . . Save and Load Simulation Data Inspector Sessions . . . . . 14-131 14-131 14-131 14-131 14-131 14-132 14-132 14-132 14-132 14-132 Custom Plot Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-134 Data Type Issues in Generated Code . . . . . . . . . . . . . . . . Enable the Highlight Option in a MATLAB Coder Project Enable the Highlight Option at the Command Line . . . . . Stowaway Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stowaway Singles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Expensive Fixed-Point Operations . . . . . . . . . . . . . . . . . . 14-136 14-136 14-136 14-136 14-136 14-136 Automated Fixed-Point Conversion Using Programmatic Workflow Convert MATLAB Code to Fixed-Point C Code . . . . . . . . . . 15-2 Propose Fixed-Point Data Types Based on Simulation Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5 Propose Fixed-Point Data Types Based on Derived Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-11 Detect Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-19 Replace the exp Function with a Lookup Table . . . . . . . . 15-23 Replace a Custom Function with a Lookup Table . . . . . . . 15-25 Enable Plotting Using the Simulation Data Inspector . . . 15-28 xvii www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualize Differences Between Floating-Point and FixedPoint Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 xviii 15-29 Setting Up a MATLAB Coder Project MATLAB Coder Project Set Up Workflow . . . . . . . . . . . . . . 16-2 Creating a New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . From the MATLAB APPS Tab . . . . . . . . . . . . . . . . . . . . . . At the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . From a MATLAB Coder Project . . . . . . . . . . . . . . . . . . . . . 16-3 16-3 16-3 16-4 Opening an Existing Project . . . . . . . . . . . . . . . . . . . . . . . . . From the MATLAB APPS Tab . . . . . . . . . . . . . . . . . . . . . . At the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . From a MATLAB Coder Project . . . . . . . . . . . . . . . . . . . . . 16-5 16-5 16-5 16-5 Adding Files to the Project . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6 Specifying Properties of Primary Function Inputs in a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Why You Must Specify Input Properties . . . . . . . . . . . . . . . How to Specify an Input Definition in a Project . . . . . . . . . . 16-7 16-7 16-7 Autodefine Input Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How MATLAB Coder Autodefines Input Types . . . . . . . . . . Prerequisites for Autodefining Input Types . . . . . . . . . . . . . How to Autodefine Input Types . . . . . . . . . . . . . . . . . . . . . . 16-8 16-8 16-8 16-8 Define Input Parameters by Example in a Project . . . . . . How to Define an Input Parameter by Example . . . . . . . . Specifying Input Parameters by Example . . . . . . . . . . . . . Specifying an Enumerated Type Input Parameter by Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying a Fixed-Point Input Parameter by Example . . . 16-15 16-16 Define or Edit Input Parameter Type in a Project . . . . . . How to Define or Edit an Input Parameter Type . . . . . . . . Specifying an Enumerated Type Input Parameter by Type 16-19 16-19 16-21 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-12 16-12 16-13 17 Specifying a Fixed-Point Input Parameter by Type . . . . . . Specifying Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-22 16-23 Define Constant Input Parameters in a Project . . . . . . . . 16-29 Define Inputs Programmatically in the MATLAB File . . . 16-30 Adding Global Variables in a Project . . . . . . . . . . . . . . . . . 16-31 Specifying Global Variable Type and Initial Value in a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Why Specify a Type Definition for Global Variables? . . . . . How to Specify a Global Variable Type . . . . . . . . . . . . . . . Defining a Global Variable by Example . . . . . . . . . . . . . . . Defining or Editing Global Variable Type . . . . . . . . . . . . . Defining Global Variable Initial Value . . . . . . . . . . . . . . . Defining Global Variable Constant Value . . . . . . . . . . . . . Removing Global Variables . . . . . . . . . . . . . . . . . . . . . . . . 16-32 16-32 16-32 16-33 16-34 16-36 16-38 16-39 Specify Output File Name . . . . . . . . . . . . . . . . . . . . . . . . . . Command Line Alternative . . . . . . . . . . . . . . . . . . . . . . . . 16-40 16-40 Specify Output File Locations . . . . . . . . . . . . . . . . . . . . . . . Command Line Alternative . . . . . . . . . . . . . . . . . . . . . . . . 16-41 16-41 Selecting Output Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Command Line Alternative . . . . . . . . . . . . . . . . . . . . . . . . Changing Output Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-42 16-42 16-42 Preparing MATLAB Code for C/C++ Code Generation Workflow for Preparing MATLAB Code for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2 17-3 Fixing Errors Detected at Design Time . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-4 17-4 Using the Code Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-5 xix www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Check Code With the Code Analyzer . . . . . . . . . . . . . . . . . . 17-6 Check Code Using the Code Generation Readiness Tool . . Run Code Generation Readiness Tool at the Command Line Run Code Generation Readiness Tool from the Current Folder Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Run the Code Generation Readiness Tool in a Project . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-8 17-8 17-8 17-8 17-9 Code Generation Readiness Tool . . . . . . . . . . . . . . . . . . . . . What Information Does the Code Generation Readiness Tool Provide? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Structure Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10 Unable to Determine Code Generation Readiness . . . . . . . 17-17 Generate MEX Functions Using the MATLAB Coder Project Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Project Workflow for Generating MEX Functions . . . . . . . Generate MEX Functions Using the Project Interface . . . . Configure Project Settings . . . . . . . . . . . . . . . . . . . . . . . . . Build a MATLAB Coder Project . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-18 17-18 17-18 17-23 17-24 17-25 17-10 17-11 17-13 17-16 Generate MEX Functions at the Command Line . . . . . . . . Command-line Workflow for Generating MEX Functions . . Generate MEX Functions at the Command Line . . . . . . . . Generating MEX Functions at the Command Line Using codegen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-26 17-26 17-26 Fix Errors Detected at Code Generation Time . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-28 17-28 17-27 17-27 Design Considerations When Writing MATLAB Code for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-29 See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-30 Running MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . xx Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17-31 17-31 Debugging Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 19 17-32 Testing MEX Functions in MATLAB Workflow for Testing MEX Functions in MATLAB . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2 18-2 Why Test MEX Functions in MATLAB? . . . . . . . . . . . . . . . . . 18-4 Running MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . 18-5 18-5 Verify MEX Functions in a Project . . . . . . . . . . . . . . . . . . . . Using Test Files That Call Only MATLAB Functions . . . . . Using Test Files That Call MEX Functions . . . . . . . . . . . . . 18-6 18-6 18-7 Verify MEX Functions at the Command Line . . . . . . . . . . . 18-8 Debug Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viewing Errors in the Run-Time Stack . . . . . . . . . . . . . . . . Handling Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . 18-9 18-9 18-10 Generating C/C++ Code from MATLAB Code Code Generation Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-3 19-3 C/C++ Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specify Custom Files to Build . . . . . . . . . . . . . . . . . . . . . . . 19-5 19-5 Generating C/C++ Static Libraries from MATLAB Code . . . Generate a C Static Library Using the Project Interface . . . Generate a C Static Library at the Command Line . . . . . . . 19-6 19-6 19-9 xxi www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان xxii Generating C/C++ Dynamically Linked Libraries from MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dynamic Libraries Generated by MATLAB Coder . . . . . . . Generate a C Dynamically Linked Library (DLL) Using the Project Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generate a C Dynamic Library at the Command Line . . . . 19-10 19-12 Generating Standalone C/C++ Executables from MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generate a C Executable Using the Project Interface . . . . . Generate a C Executable at the Command Line . . . . . . . . Specifying main Functions for C/C++ Executables . . . . . . . Specify main Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-13 19-13 19-15 19-16 19-17 Build Setting Configuration . . . . . . . . . . . . . . . . . . . . . . . . . Specify Output Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specify a Language for Code Generation . . . . . . . . . . . . . . Specify Data Type Used in Generated Code . . . . . . . . . . . . Specify Output File Name . . . . . . . . . . . . . . . . . . . . . . . . . Specify Output File Locations . . . . . . . . . . . . . . . . . . . . . . Parameter Specification Methods . . . . . . . . . . . . . . . . . . . Specify Build Configuration Parameters . . . . . . . . . . . . . . 19-19 19-19 19-21 19-22 19-23 19-24 19-25 19-25 Standard Math Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-32 Change the Standard Math Library . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-33 19-33 Share Build Configuration Settings . . . . . . . . . . . . . . . . . . Export Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Import Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-34 19-34 19-35 19-36 Convert MATLAB Coder Project to MATLAB Script . . . . . 19-37 Primary Function Input Specification . . . . . . . . . . . . . . . . Why You Must Specify Input Properties . . . . . . . . . . . . . . Properties to Specify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Rules for Specifying Properties of Primary Inputs . . . . . . . Methods for Defining Properties of Primary Inputs . . . . . . Define Input Properties by Example at the Command Line Specify Constant Inputs at the Command Line . . . . . . . . . Specify Variable-Size Inputs at the Command Line . . . . . . 19-39 19-39 19-39 19-42 19-43 19-44 19-46 19-47 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19-10 19-10 Control Constant Inputs in MEX Function Signatures . . . Control MEX Function Signature Using the Project Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Control MEX Function Signature at the Command-Line Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Options for Controlling Constant Inputs in MEX Function Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Call MEX Function with a Constant Input . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-49 19-49 19-49 19-49 19-51 19-52 Define Input Properties Programmatically in the MATLAB File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How to Use assert with MATLAB Coder . . . . . . . . . . . . . . Rules for Using assert Function . . . . . . . . . . . . . . . . . . . . Specifying General Properties of Primary Inputs . . . . . . . . Specifying Properties of Primary Fixed-Point Inputs . . . . . Specifying Class and Size of Scalar Structure . . . . . . . . . . Specifying Class and Size of Structure Array . . . . . . . . . . 19-53 19-53 19-59 19-59 19-60 19-61 19-62 Speed Up Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generate Code Only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Disable Compiler Optimization . . . . . . . . . . . . . . . . . . . . . 19-63 19-63 19-63 Paths and File Infrastructure Setup . . . . . . . . . . . . . . . . . . Compile Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . Specifying Folders to Search for Custom Code . . . . . . . . . . Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-65 19-65 19-65 19-66 Generate Code for Multiple Entry-Point Functions . . . . . 19-70 Advantages of Generating Code for More Than One Entry-Point Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-70 Generating Code for More Than One Entry-Point Function Using the Project Interface . . . . . . . . . . . . . . . . . . . . . . 19-70 Generating Code for More Than One Entry-Point Function at the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-72 How to Call an Entry-Point Function in a MEX Function . 19-74 How to Call an Entry-Point Function in a C/C++ Library Function from C/C++ Code . . . . . . . . . . . . . . . . . . . . . . 19-74 Generate Code for Global Data . . . . . . . . . . . . . . . . . . . . . . Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declare Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . Define Global Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-75 19-75 19-75 19-76 xxiii www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Synchronizing Global Data with MATLAB . . . . . . . . . . . . Define Constant Global Data . . . . . . . . . . . . . . . . . . . . . . . Limitations of Using Global Data . . . . . . . . . . . . . . . . . . . 19-77 19-80 19-83 Generation of Traceable Code . . . . . . . . . . . . . . . . . . . . . . . About Code Traceability . . . . . . . . . . . . . . . . . . . . . . . . . . Generate Traceable Code . . . . . . . . . . . . . . . . . . . . . . . . . . Format of Traceability Tags . . . . . . . . . . . . . . . . . . . . . . . Location of Comments in Generated Code . . . . . . . . . . . . . Traceability Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . 19-84 19-84 19-84 19-87 19-87 19-91 Generate Code for Enumerated Types . . . . . . . . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-93 19-93 Generate Code for Variable-Size Data . . . . . . . . . . . . . . . . 19-94 Disable Support for Variable-Size Data . . . . . . . . . . . . . . . 19-94 Control Dynamic Memory Allocation . . . . . . . . . . . . . . . . . 19-95 Generating Code for MATLAB Functions with Variable-Size Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-97 Generate Code for a MATLAB Function That Expands a Vector in a Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-98 Using Dynamic Memory Allocation for an "Atoms" Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-104 xxiv Code Generation for MATLAB Classes . . . . . . . . . . . . . . . 19-113 How MATLAB Coder Partitions Generated Code . . . . . . Partitioning Generated Files . . . . . . . . . . . . . . . . . . . . . . How to Select the File Partitioning Method . . . . . . . . . . . Partitioning Generated Files with One C/C++ File Per MATLAB File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generated Files and Locations . . . . . . . . . . . . . . . . . . . . File Partitioning and Inlining . . . . . . . . . . . . . . . . . . . . . 19-114 19-114 19-114 Requirements for Signed Integer Representation . . . . . . 19-126 Customize the Post-Code-Generation Build Process . . . . Customize Build Using coder.updateBuildInfo . . . . . . . . . Customize Build Using Post-Code-Generation Command . Build Information Object . . . . . . . . . . . . . . . . . . . . . . . . . Build Information Methods . . . . . . . . . . . . . . . . . . . . . . . Write Post-Code-Generation Command . . . . . . . . . . . . . . Use Post-Code-Generation Command to Customize Build 19-127 19-127 19-127 19-128 19-128 19-164 19-165 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19-115 19-120 19-122 Write and Use Post-Code-Generation Command at the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 19-165 Code Generation Reports . . . . . . . . . . . . . . . . . . . . . . . . . . About Code Generation Reports . . . . . . . . . . . . . . . . . . . Enable Code Generation Reports . . . . . . . . . . . . . . . . . . . View Your MATLAB Code in a Report . . . . . . . . . . . . . . Viewing Call Stack Information . . . . . . . . . . . . . . . . . . . View Generated C and C++ Code in a Report . . . . . . . . . View the Build Summary Information . . . . . . . . . . . . . . . View Errors and Warnings in a Report . . . . . . . . . . . . . . Viewing Variables in Your MATLAB Code . . . . . . . . . . . View Target Build Information . . . . . . . . . . . . . . . . . . . . Keyboard Shortcuts for the Code Generation Report . . . . Report Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-167 19-167 19-170 19-170 19-172 19-174 19-174 19-175 19-176 19-182 19-183 19-184 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Run-time Stack Overflow . . . . . . . . . . . . . . . . . . . . . . . . 19-186 19-186 Package Code For Other Development Environments . . When to Package Code . . . . . . . . . . . . . . . . . . . . . . . . . . Package Generated Code in a Project . . . . . . . . . . . . . . . Package Generated Code at the Command Line . . . . . . . Specify packNGo options . . . . . . . . . . . . . . . . . . . . . . . . . 19-187 19-187 19-187 19-188 19-189 Code Replacement for MATLAB Code What Is Code Replacement? . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2 Code Replacement Libraries . . . . . . . . . . . . . . . . . . . . . . . . . 20-4 Code Replacement Terminology . . . . . . . . . . . . . . . . . . . . . . 20-6 Code Replacement Limitations . . . . . . . . . . . . . . . . . . . . . . . 20-9 Replace Code Generated from MATLAB Code . . . . . . . . . . 20-10 Choose a Code Replacement Library . . . . . . . . . . . . . . . . . About Choosing a Code Replacement Library . . . . . . . . . . 20-12 20-12 xxv www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Explore Available Code Replacement Libraries . . . . . . . . . Explore Code Replacement Library Contents . . . . . . . . . . 21 xxvi 20-12 20-12 Custom Toolchain Registration Custom Toolchain Registration . . . . . . . . . . . . . . . . . . . . . . . What Is a Custom Toolchain? . . . . . . . . . . . . . . . . . . . . . . . What Is a Factory Toolchain? . . . . . . . . . . . . . . . . . . . . . . . What is a Toolchain Definition? . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typical Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2 21-2 21-2 21-3 21-4 21-4 About coder.make.ToolchainInfo . . . . . . . . . . . . . . . . . . . . . . 21-6 Create and Edit Toolchain Definition File . . . . . . . . . . . . . . 21-8 Toolchain Definition File with Commentary . . . . . . . . . . . Steps Involved in Writing a Toolchain Definition File . . . . Write a Function That Creates a ToolchainInfo Object . . . Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Archiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Build Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-10 21-10 21-10 21-11 21-11 21-12 21-12 21-13 21-13 21-14 21-14 Create and Validate ToolchainInfo Object . . . . . . . . . . . . . 21-16 Register the Custom Toolchain . . . . . . . . . . . . . . . . . . . . . . 21-17 Use the Custom Toolchain . . . . . . . . . . . . . . . . . . . . . . . . . . 21-19 Troubleshooting Custom Toolchain Validation . . . . . . . . . Build Tool Command Path Incorrect . . . . . . . . . . . . . . . . . Build Tool Not in System Path . . . . . . . . . . . . . . . . . . . . . Tool Path Does Not Exist . . . . . . . . . . . . . . . . . . . . . . . . . Unsupported Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-20 21-20 21-20 21-21 21-21 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 22 Toolchain is Not installed . . . . . . . . . . . . . . . . . . . . . . . . . Project or Configuration is Using the Template Makefile . . Skipped Validation of Build Tool “Download” or “Execute” . 21-22 21-22 21-23 Prevent Circular Data Dependencies with One-Pass or Single-Pass Linkers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-24 Deploying Generated Code Call a C Static Library Function from C Code . . . . . . . . . . . 22-2 Call a C/C++ Static Library Function from MATLAB Code . 22-4 Call Generated C/C++ Functions . . . . . . . . . . . . . . . . . . . . . . Conventions for Calling Functions in Generated Code . . . . . How to Call C/C++ Functions from MATLAB Code . . . . . . . Calling Initialize and Terminate Functions . . . . . . . . . . . . . Calling C/C++ Functions with Multiple Outputs . . . . . . . . . Calling C/C++ Functions that Return Arrays . . . . . . . . . . . 22-6 22-6 22-6 22-7 22-8 22-8 Use a MATLAB Coder Dynamic Library in a Simple Microsoft Visual Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-9 Specify External File Locations . . . . . . . . . . . . . . . . . . . . . . External File Locations for External Code Integration . . . . Specify External Files in a Class Derived from coder.ExternalDependency . . . . . . . . . . . . . . . . . . . . . . . Specify External Files in MATLAB Code Using coder.updateBuildInfo . . . . . . . . . . . . . . . . . . . . . . . . . . Specify External Files in the Project Settings Dialog Box . . Specify External Files at the Command Line . . . . . . . . . . . Specify External Files with Configuration Objects . . . . . . . 22-12 22-12 22-12 22-12 22-13 22-13 22-14 xxvii www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 23 Accelerating MATLAB Algorithms Workflow for Accelerating MATLAB Algorithms . . . . . . . . . See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Best Practices for Using MEX Functions to Accelerate MATLAB Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Accelerate Code That Dominates Execution Time . . . . . . . . Include Loops Inside MEX Function . . . . . . . . . . . . . . . . . . Avoid Generating MEX Functions from Unsupported Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Avoid Generating MEX Functions if Built-In MATLAB Functions Dominate Run Time . . . . . . . . . . . . . . . . . . . . Minimize MEX Function Calls . . . . . . . . . . . . . . . . . . . . . . Edge Detection on Images . . . . . . . . . . . . . . . . . . . . . . . . . . . xxviii 23-2 23-3 23-4 23-4 23-4 23-5 23-6 23-6 23-7 Accelerate MATLAB Algorithms . . . . . . . . . . . . . . . . . . . . . 23-14 Modifying MATLAB Code for Acceleration . . . . . . . . . . . . How to Modify Your MATLAB Code for Acceleration . . . . . 23-15 23-15 Control Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . Types of Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . When to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . How to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . . 23-16 23-16 23-16 23-17 Algorithm Acceleration Using Parallel for-Loops (parfor) Parallel for-Loops (parfor) in Generated Code . . . . . . . . . . How parfor-Loops Improve Execution Speed . . . . . . . . . . . When to Use parfor-Loops . . . . . . . . . . . . . . . . . . . . . . . . . When Not to Use parfor-Loops . . . . . . . . . . . . . . . . . . . . . parfor-Loop Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . parfor Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-18 23-18 23-19 23-19 23-19 23-20 23-20 Control Compilation of parfor-Loops . . . . . . . . . . . . . . . . . When to Disable parfor . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-24 23-24 Reduction Assignments in parfor-Loops . . . . . . . . . . . . . . . What are Reduction Assignments? . . . . . . . . . . . . . . . . . . Multiple Reductions in a parfor-Loop . . . . . . . . . . . . . . . . 23-25 23-25 23-25 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Classification of Variables in parfor-Loops . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sliced Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Broadcast Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Reduction Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Temporary Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-26 23-26 23-27 23-28 23-28 23-33 Accelerate MATLAB Algorithms That Use Parallel for-Loops (parfor) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-35 24 Specify Maximum Number of Threads in parfor-Loops . . 23-36 Troubleshooting parfor-Loops . . . . . . . . . . . . . . . . . . . . . . . What Causes Errors With Global Structures in Parallel Regions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compiler Does Not Support OpenMP . . . . . . . . . . . . . . . . 23-37 Accelerating Simulation of Bouncing Balls . . . . . . . . . . . . 23-38 23-37 23-37 Calling C/C++ Functions from Generated Code External Function Calls from Generated Code . . . . . . . . . . Calling External Functions from Generated Code . . . . . . . . Why Call External Functions from Generated Code? . . . . . . How To Call External Functions . . . . . . . . . . . . . . . . . . . . . Pass Arguments by Reference to External Functions . . . . . . Manipulate C Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2 24-2 24-2 24-2 24-3 24-4 Call External Functions Using coder.ceval . . . . . . . . . . . . . Workflow for Calling External Functions . . . . . . . . . . . . . . Best Practices for Calling External Code from Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-6 24-6 Return Multiple Values from C Functions . . . . . . . . . . . . . . 24-8 How MATLAB Coder Infers C/C++ Data Types . . . . . . . . . . Mapping MATLAB Types to C/C++ Types . . . . . . . . . . . . . . Mapping 64-Bit Integer Types to C/C++ . . . . . . . . . . . . . . Mapping Fixed-Point Types to C/C++ . . . . . . . . . . . . . . . . 24-9 24-9 24-10 24-11 24-7 xxix www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Mapping Mapping Mapping Mapping Mapping 25 26 xxx Arrays to C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . Complex Values to C/C++ . . . . . . . . . . . . . . . . . . Structures to C/C++ Structures . . . . . . . . . . . . . Strings to C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . Multiword Types to C/C++ . . . . . . . . . . . . . . . . . 24-11 24-12 24-13 24-13 24-14 External Code Integration External Code Integration for Code Generation . . . . . . . . . 25-2 Encapsulating the Interface to External Code . . . . . . . . . . . 25-3 Best Practices for Using coder.ExternalDependency . . . . . Terminate Code Generation for Unsupported External Dependency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Parameterize Methods for MATLAB and Generated Code . . Parameterize updateBuildInfo for Multiple Platforms . . . . . 25-4 25-4 25-4 25-5 Encapsulate Interface to an External C Library . . . . . . . . . 25-6 Update Build Information from MATLAB code . . . . . . . . . . 25-9 Call External Functions Encapsulated by coder.ExternalDependency . . . . . . . . . . . . . . . . . . . . . . . . 25-10 Generate Efficient and Reusable Code Optimization Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-2 Modularize MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-5 Eliminate Redundant Copies of Function Inputs . . . . . . . . 26-6 Inline Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Prevent Function Inlining . . . . . . . . . . . . . . . . . . . . . . . . . . 26-8 26-8 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use Inlining in Control Flow Statements . . . . . . . . . . . . . . 26-8 Control Inlining Using Configuration Object . . . . . . . . . . . Control Size of Functions Inlined . . . . . . . . . . . . . . . . . . . Control Size of Functions After Inlining . . . . . . . . . . . . . . Control Stack Size Limit on Inlined Functions . . . . . . . . . 26-10 26-10 26-11 26-11 Fold Function Calls into Constants . . . . . . . . . . . . . . . . . . . 26-13 Control Stack Space Usage . . . . . . . . . . . . . . . . . . . . . . . . . . 26-15 Stack Allocation and Performance . . . . . . . . . . . . . . . . . . . 26-16 Rewrite Logical Array Indexing as a Loop . . . . . . . . . . . . . 26-17 Dynamic Memory Allocation and Performance . . . . . . . . . When Dynamic Memory Allocation Occurs . . . . . . . . . . . . 26-18 26-18 Minimize Dynamic Memory Allocation . . . . . . . . . . . . . . . . 26-19 Provide Maximum Size for Variable-Size Arrays . . . . . . . . 26-20 Disable Dynamic Memory Allocation During Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-26 Set Dynamic Memory Allocation Threshold . . . . . . . . . . . . Set Dynamic Memory Allocation Threshold Using Project Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Set Dynamic Memory Allocation Threshold from Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-27 Excluding Unused Paths from Generated Code . . . . . . . . . 26-30 Prevent Code Generation for Unused Execution Paths . . Prevent Code Generation When Local Variable Controls Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Prevent Code Generation When Input Variable Controls Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-31 Generate Code with Parallel for-Loops (parfor) . . . . . . . . 26-33 Minimize Redundant Operations in Loops . . . . . . . . . . . . . 26-35 26-27 26-29 26-31 26-32 xxxi www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان xxxii Unroll for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limit Copying the for-loop Body in Generated Code . . . . . 26-37 26-37 Support for Integer Overflow and Non-Finites . . . . . . . . . Disable Support for Integer Overflow . . . . . . . . . . . . . . . . Disable Support for Non-Finites . . . . . . . . . . . . . . . . . . . . 26-40 26-40 26-41 Integrate Custom Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-42 MATLAB Coder Optimizations in Generated Code . . . . . . Constant Folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loop Fusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Successive Matrix Operations Combined . . . . . . . . . . . . . . Unreachable Code Elimination . . . . . . . . . . . . . . . . . . . . . 26-48 26-48 26-49 26-49 26-50 Generate Reusable Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-51 Contents www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 About MATLAB Coder • “MATLAB Coder Product Description” on page 1-2 • “Product Overview” on page 1-3 • “Code Generation Workflow” on page 1-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 About MATLAB Coder MATLAB Coder Product Description Generate C and C++ code from MATLAB code MATLAB® Coder™ generates standalone C and C++ code from MATLAB code. The generated source code is portable and readable. MATLAB Coder supports a subset of core MATLAB language features, including program control constructs, functions, and matrix operations. It can generate MEX functions that let you accelerate computationally intensive portions of MATLAB code and verify the behavior of the generated code. Key Features • ANSI®/ISO® compliant C and C++ code generation • MEX function generation for fixed-point and floating-point math • Project management tool for specifying entry points, input data properties, and other code-generation configuration options • Static or dynamic memory allocation for variable-size data • Code generation support for many functions and System objects in Communications System Toolbox™, DSP System Toolbox™, Computer Vision System Toolbox™, and Phased Array System Toolbox™ • Support for common MATLAB language features, including matrix operations, subscripting, program controls statements (if, switch, for, while), and structures 1-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Product Overview Product Overview In this section... “When to Use MATLAB Coder” on page 1-3 “Code Generation for Embedded Software Applications” on page 1-3 “Code Generation for Fixed-Point Algorithms” on page 1-3 When to Use MATLAB Coder Use MATLAB Coder to: • Generate readable, efficient, standalone C/C++ code from MATLAB code. • Generate MEX functions from MATLAB code to: • Accelerate your MATLAB algorithms. • Verify generated C code within MATLAB. • Integrate custom C/C++ code into MATLAB. Code Generation for Embedded Software Applications The Embedded Coder® product extends the MATLAB Coder product with features that are important for embedded software development. Using the Embedded Coder addon product, you can generate code that has the clarity and efficiency of professional handwritten code. For example, you can: • Generate code that is compact and fast, which is essential for real-time simulators, on-target rapid prototyping boards, microprocessors used in mass production, and embedded systems. • Customize the appearance of the generated code. • Optimize the generated code for a specific target environment. • Enable tracing options that help you to verify the generated code. • Generate reusable, reentrant code. Code Generation for Fixed-Point Algorithms Using the Fixed-Point Designer™ product, you can generate: 1-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 About MATLAB Coder • MEX functions to accelerate fixed-point algorithms. • Fixed-point code that provides a bit-wise match to MEX function results. 1-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Code Generation Workflow Code Generation Workflow See Also • “MATLAB Coder Project Set Up Workflow” • “Workflow for Preparing MATLAB Code for Code Generation” • “Workflow for Testing MEX Functions in MATLAB” • “Code Generation Workflow” • “Workflow for Accelerating MATLAB Algorithms” 1-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-6 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Design Considerations for C/C++ Code Generation • “When to Generate Code from MATLAB Algorithms” on page 2-2 • “Which Code Generation Feature to Use” on page 2-4 • “Prerequisites for C/C++ Code Generation from MATLAB” on page 2-5 • “MATLAB Code Design Considerations for Code Generation” on page 2-6 • “Differences in Behavior After Compiling MATLAB Code” on page 2-8 • “MATLAB Language Features Supported for C/C++ Code Generation” on page 2-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Design Considerations for C/C++ Code Generation When to Generate Code from MATLAB Algorithms Generating code from MATLAB algorithms for desktop and embedded systems allows you to perform your software design, implementation, and testing completely within the MATLAB workspace. You can: • Verify that your algorithms are suitable for code generation • Generate efficient, readable, and compact C/C++ code automatically, which eliminates the need to manually translate your MATLAB algorithms and minimizes the risk of introducing errors in the code. • Modify your design in MATLAB code to take into account the specific requirements of desktop and embedded applications, such as data type management, memory use, and speed. • Test the generated code and easily verify that your modified algorithms are functionally equivalent to your original MATLAB algorithms. • Generate MEX functions to: • Accelerate MATLAB algorithms in certain applications. • Speed up fixed-point MATLAB code. • Generate hardware description language (HDL) from MATLAB code. When Not to Generate Code from MATLAB Algorithms Do not generate code from MATLAB algorithms for the following applications. Use the recommended MathWorks product instead. To: Use: Deploy an application that uses handle graphics MATLAB Compiler™ Use Java® MATLAB Builder™ JA Use toolbox functions that do not support code generation Toolbox functions that you rewrite for desktop and embedded applications Deploy MATLAB based GUI applications on a supported MATLAB host MATLAB Compiler Deploy web-based or Windows® applications • MATLAB Builder NE • MATLAB Builder JA 2-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان When to Generate Code from MATLAB Algorithms To: Use: Interface C code with MATLAB MATLAB mex function 2-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Design Considerations for C/C++ Code Generation Which Code Generation Feature to Use To... Use... Required Product To Explore Further... Generate MEX codegen function functions for verifying generated code MATLAB Coder Try this in “MEX Function Generation at the Command Line”. Produce readable, MATLAB Coder user efficient, and compact interface code from MATLAB algorithms for codegen function deployment to desktop and embedded systems. MATLAB Coder Try this in “C Code Generation Using the Project Interface”. MATLAB Coder Try this in “C Code Generation at the Command Line”. Generate MEX MATLAB Coder user functions to accelerate interface MATLAB algorithms codegen function MATLAB Coder See “Accelerate MATLAB Algorithms”. Integrate MATLAB code into Simulink® MATLAB Function block Simulink Try this in “Track Object Using MATLAB Code”. Speed up fixed-point MATLAB code fiaccel function Fixed-Point Designer Learn more in “Code Acceleration and Code Generation from MATLAB”. MATLAB Coder Learn more in “Specify External File Locations”. Integrate custom C codegen function code into MATLAB and generate efficient, readable code MATLAB Coder Integrate custom C code into code generated from MATLAB coder.ceval function MATLAB Coder Learn more in coder.ceval. Generate HDL from MATLAB code MATLAB Function block Learn more at www.mathworks.com/ products/ slhdlcoder. Simulink and HDL Coder™ 2-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Prerequisites for C/C++ Code Generation from MATLAB Prerequisites for C/C++ 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 2-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Design Considerations for C/C++ Code Generation MATLAB Code Design Considerations for Code Generation When writing MATLAB code that you want to convert into efficient, standalone C/C++ code, you must consider the following: • Data types C and C++ use static typing. To determine the types of your variables before use, MATLAB Coder requires a complete assignment to each variable. • Array sizing Variable-size arrays and matrices are supported for code generation. You can define inputs, outputs, and local variables in MATLAB functions to represent data that varies in size at run time. • Memory You can choose whether the generated code uses static or dynamic memory allocation. With dynamic memory allocation, you potentially use less memory at the expense of time to manage the memory. With static memory, you get better speed, but with higher memory usage. Most MATLAB code takes advantage of the dynamic sizing features in MATLAB, therefore dynamic memory allocation typically enables you to generate code from existing MATLAB code without modifying it much. Dynamic memory allocation also allows some programs to compile even when upper bounds cannot be found. Static allocation reduces the memory footprint of the generated code, and therefore is suitable for applications where there is a limited amount of available memory, such as embedded applications. • Speed Because embedded applications must run in real time, the code must be fast enough to meet the required clock rate. To improve the speed of the generated code: • Choose a suitable C/C++ compiler. Do not use the default compiler that MathWorks supplies with MATLAB for Windows 32-bit platforms. • Consider disabling run-time checks. 2-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB Code Design Considerations for Code Generation By default, for safety, the code generated for your MATLAB code contains memory integrity checks and responsiveness checks. Generally, these checks result in more generated code and slower simulation. Disabling run-time checks usually results in streamlined generated code and faster simulation. Disable these checks only if you have verified that array bounds and dimension checking is unnecessary. See Also • “Data Definition Basics” • “Variable-Size Data” • “Bounded Versus Unbounded Variable-Size Data” • “Control Dynamic Memory Allocation” • “Control Run-Time Checks” 2-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Design Considerations for C/C++ Code Generation Differences in Behavior After Compiling MATLAB Code In this section... “Why Are There Differences?” on page 2-8 “Character Size” on page 2-8 “Order of Evaluation in Expressions” on page 2-8 “Termination Behavior” on page 2-9 “Size of Variable-Size N-D Arrays” on page 2-9 “Size of Empty Arrays” on page 2-9 “Floating-Point Numerical Results” on page 2-10 “NaN and Infinity Patterns” on page 2-10 “Code Generation Target” on page 2-11 “MATLAB Class Initial Values” on page 2-11 “Variable-Size Support for Code Generation” on page 2-11 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 6-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: • Modify persistent or global variables 2-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Differences in Behavior After Compiling MATLAB Code • Display data to the screen • Write data to files • Modify the properties of handle class objects 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 do not have 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 7-27. Size of Empty Arrays The size of an empty array in generated code might be different from its size in MATLAB source code. See “Incompatibility with MATLAB in Determining Size of Empty Arrays” on page 7-28. 2-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Design Considerations for C/C++ Code Generation 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 floatingpoint 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 platformspecific 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. 2-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان For implementation of BLAS library functions 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 is executing in MATLAB or has been compiled for a simulation or code generation target. See coder.target. MATLAB Class Initial Values MATLAB computes class initial values at class loading time before code generation. The code generation software uses the value that MATLAB computed, it does not recompute the initial value. If the initialization uses a function call to compute the initial value, the code generation software does not execute this function. If the function modifies a global state, for example, a persistent variable, code generation software might provide a different initial value than MATLAB. For more information, see “Defining Class Properties for Code Generation”. Variable-Size Support for Code Generation For incompatibilities with MATLAB in variable-size support for code generation, see: • “Incompatibility with MATLAB for Scalar Expansion” • “Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays” • “Incompatibility with MATLAB in Determining Size of Empty Arrays” • “Incompatibility with MATLAB in Vector-Vector Indexing” • “Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation” 2-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Design Considerations for C/C++ Code Generation MATLAB Language Features Supported for C/C++ Code Generation MATLAB supports the following language features in generated code: • N-dimensional arrays (see “Array Size Restrictions for Code Generation” on page 6-7) • Matrix operations, including deletion of rows and columns • Variable-sized data (see “Variable-Size Data Definition for Code Generation” on page 7-3) • Subscripting (see “Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation” on page 7-30) • Complex numbers (see “Code Generation for Complex Data” on page 6-4) • Numeric classes (see “Supported Variable Types” on page 5-17) • Double-precision, single-precision, and integer math • Fixed-point arithmetic (see “Code Acceleration and Code Generation from MATLAB”) • Program control statements if, switch, for, while, and break • Arithmetic, relational, and logical operators • Local functions • Persistent variables (see “Define and Initialize Persistent Variables” on page 5-10) • Global variables (see “Specifying Global Variable Type and Initial Value in a Project”). • Structures • Characters (see “Code Generation for Characters” on page 6-6) • Function handles • Frames • Variable length input and output argument lists • Subset of MATLAB toolbox functions • MATLAB classes • Ability to call functions (see “Resolution of Function Calls for Code Generation” on page 13-2) MATLAB Language Features Not Supported for C/C++ Code Generation MATLAB does not support the following features in generated code: 2-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB Language Features Supported for C/C++ Code Generation • Anonymous functions • Cell arrays • Java • Nested functions • Recursion • Sparse matrices • try/catch statements 2-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-14 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3 System Objects Supported for Code Generation www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3 System Objects Supported for Code Generation Code Generation for System Objects You can generate C and C++ code for a subset of System objects provided by the following toolboxes. Toolbox Name See Communications System Toolbox “System Objects in MATLAB Code Generation” in the DSP System Toolbox documentation. Computer Vision System Toolbox “System Objects in MATLAB Code Generation” in the Computer Vision System Toolbox documentation. DSP System Toolbox “System Objects in MATLAB Code Generation” in the DSP System Toolbox documentation. Image Acquisition Toolbox™ • imaq.VideoDevice. • “Code Generation with VideoDevice System Object” in the Image Acquisition Toolbox documentation. Phased Array System Toolbox “Code Generation” in the Phased Array System Toolbox documentation. To use these System objects, you need to install the requisite toolbox. For a list of System objects supported for C and C++ code generation, see “Functions and Objects Supported for C and C++ Code Generation — Alphabetical List” and “Functions and Objects Supported for C and C++ Code Generation — Category List”. 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 about MATLAB objects, see “Begin Using Object-Oriented Programming”. 3-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation • “Functions and Objects Supported for C and C++ Code Generation — Alphabetical List” on page 4-2 • “Functions and Objects Supported for C and C++ Code Generation — Category List” on page 4-134 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Functions and Objects Supported for C and C++ Code Generation — Alphabetical List You can generate efficient C and C++ code for a subset of MATLAB built-in functions and toolbox functions, classes, and System objects that you call from MATLAB code. These function, classes, and System objects appear in alphabetical order in the following table. To find supported functions, classes, and System objects by MATLAB category or toolbox, see “Functions and Objects Supported for C and C++ Code Generation — Category List”. Note: For more information on code generation for fixed-point algorithms, refer to “Code Acceleration and Code Generation from MATLAB”. Name Product Remarks and Limitations abs MATLAB — abs Fixed-Point Designer — accumneg Fixed-Point Designer — accumpos Fixed-Point Designer — acos 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). acosd MATLAB — acosh 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). 4-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Alphabetical List Name Product Remarks and Limitations acot MATLAB — acotd MATLAB — acoth MATLAB — acsc MATLAB — acscd MATLAB — acsch MATLAB — add Fixed-Point Designer Code generation in MATLAB does not support the syntax F.add(a,b). You must use the syntax add(F,a,b). affine2d Image Processing When generating code, you can only specify Toolbox™ single objects—arrays of objects are not supported. aictest Phased Array System Toolbox Does not support variable-size inputs. albersheim Phased Array System Toolbox Does not support variable-size inputs. all MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” all Fixed-Point Designer — ambgfun Phased Array System Toolbox Does not support variable-size inputs. and MATLAB — any MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” any Fixed-Point Designer — aperture2gain Phased Array System Toolbox Does not support variable-size inputs. asec MATLAB — asecd MATLAB — 4-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations asech MATLAB — asin 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). asind MATLAB — asinh MATLAB — assert MATLAB • 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. • For standalone code generation, excluded from the generated code. • See “Rules for Using assert Function”. assignDetectionsToTracks Computer Vision Compile-time constant input: No restriction. System Toolbox Supports MATLAB Function block: Yes atan MATLAB — atan2 MATLAB — atan2 Fixed-Point Designer — atan2d MATLAB — atand MATLAB — atanh 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). az2broadside Phased Array System Toolbox Does not support variable-size inputs. 4-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations azel2phitheta Phased Array System Toolbox Does not support variable-size inputs. azel2phithetapat Phased Array System Toolbox Does not support variable-size inputs. azel2uv Phased Array System Toolbox Does not support variable-size inputs. azel2uvpat Phased Array System Toolbox Does not support variable-size inputs. azelaxes Phased Array System Toolbox Does not support variable-size inputs. barthannwin Signal Processing Window length must be a constant. Expressions Toolbox™ 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 “Specify Constant Inputs at the Command Line”. bartlett Signal Processing Window length must be a constant. Expressions Toolbox 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 “Specify Constant Inputs at the Command Line”. bboxOverlapRatio Computer Vision Compile-time constant input: No restriction System Toolbox Supports MATLAB Function block: No beat2range Phased Array System Toolbox Does not support variable-size inputs. 4-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations besselap Signal Processing Filter order must be a constant. Expressions Toolbox 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 “Specify Constant Inputs at the Command Line”. beta MATLAB — betacdf Statistics Toolbox™ — betainc MATLAB Always returns a complex result. betaincinv MATLAB Always returns a complex result. betainv Statistics Toolbox — betaln MATLAB betapdf Statistics Toolbox — betarnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: — • The output is nonscalar. • An input parameter is invalid for the distribution. betastat Statistics Toolbox — bi2de Communications — System Toolbox billingsleyicm Phased Array System Toolbox Does not support variable-size inputs. bin2dec MATLAB • Does not match MATLAB when the input is empty. binaryFeatures Computer Vision — System Toolbox 4-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations binocdf Statistics Toolbox — binoinv Statistics Toolbox — binopdf Statistics Toolbox — binornd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. binostat Statistics Toolbox — bitand MATLAB — bitand Fixed-Point Designer • Not supported for slope-bias scaled fi objects. bitandreduce Fixed-Point Designer — bitcmp MATLAB — bitcmp Fixed-Point Designer — bitconcat Fixed-Point Designer — bitget MATLAB — bitget Fixed-Point Designer — bitmax MATLAB — bitor MATLAB — bitor Fixed-Point Designer • Not supported for slope-bias scaled fi objects. bitorreduce Fixed-Point Designer — bitreplicate Fixed-Point Designer — 4-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations bitrevorder Signal Processing — Toolbox bitrol Fixed-Point Designer — bitror Fixed-Point Designer — bitset MATLAB — bitset Fixed-Point Designer — bitshift MATLAB — bitshift Fixed-Point Designer — bitsliceget Fixed-Point Designer — bitsll Fixed-Point Designer • Generated code may not handle out of range shifting. bitsra Fixed-Point Designer • Generated code may not handle out of range shifting. bitsrl Fixed-Point Designer • Generated code may not handle out of range shifting. bitxor MATLAB — bitxor Fixed-Point Designer • Not supported for slope-bias scaled fi objects. bitxorreduce Fixed-Point Designer — 4-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations blackman Signal Processing Window length must be a constant. Expressions Toolbox 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 “Specify Constant Inputs at the Command Line”. blackmanharris Signal Processing Window length must be a constant. Expressions Toolbox 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 “Specify Constant Inputs at the Command Line”. blanks MATLAB — blkdiag MATLAB — bohmanwin Signal Processing Window length must be a constant. Expressions Toolbox 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 “Specify Constant Inputs at the Command Line”. break MATLAB — 4-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations BRISKPoints Computer Vision Compile-time constant inputs: No restriction System Toolbox Supports MATLAB Function block: No To index locations with this object, use the syntax: points.Location(idx,:), for points object. See visionRecovertformCodeGeneration_kernel.m, which is used in the “Introduction to Code Generation with Feature Matching and Registration” example. broadside2az Phased Array System Toolbox Does not support variable-size inputs. bsxfun MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” buttap Signal Processing Filter order must be a constant. Expressions Toolbox 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 “Specify Constant Inputs at the Command Line”. butter Signal Processing Filter coefficients must be constants. Toolbox 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 “Specify Constant Inputs at the Command Line”. 4-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations buttord Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. bwdist Image Processing The method argument must be a compile-time Toolbox constant. Input images must have fewer than 232 pixels. Generated code for this function uses a precompiled, “platform-specific shared library”. bwlookup Image Processing • For best results, specify an input image of Toolbox class logical. bwmorph Image Processing • The text string specifying the operation must Toolbox be a constant and, for best results, specify an input image of class logical. bwpack Image Processing Generated code for this function uses a Toolbox precompiled platform-specific shared library. bwselect Image Processing Supports only the 3 and 4 input argument Toolbox syntaxes: BW2 = bwselect(BW,c,r) and BW2 = bwselect(BW,c,r,n). The optional fourth input argument, n, must be a compiletime constant. In addition, with code generation, bwselect only supports only the 1 and 2 output argument syntaxes: BW2 = bwselect(___) or [BW2, idx] = bwselect(___). Generated code for this function uses a precompiled platform-specific shared library. 4-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations bwtraceboundary Image Processing The dir, fstep, and conn arguments must be Toolbox compile-time constants. bwunpack Image Processing Generated code for this function uses a Toolbox precompiled platform-specific shared library. ca2tf DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. cart2pol MATLAB — cart2sph MATLAB — cart2sphvec Phased Array System Toolbox Does not support variable-size inputs. cast MATLAB — cat MATLAB • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” cbfweights Phased Array System Toolbox Does not support variable-size inputs. cdf Statistics Toolbox — ceil MATLAB — ceil Fixed-Point Designer — cfirpm Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. char MATLAB — 4-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations cheb1ap Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. cheb1ord Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. cheb2ap Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. 4-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations cheb2ord Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. chebwin Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. cheby1 Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. 4-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations cheby2 Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. chi2cdf Statistics Toolbox — chi2inv Statistics Toolbox — chi2pdf Statistics Toolbox — chi2rnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. chi2stat Statistics Toolbox — chol MATLAB — circpol2pol Phased Array System Toolbox Does not support variable-size inputs. circshift MATLAB — cl2tf DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. class MATLAB — 4-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations colon MATLAB • Does not accept complex inputs. • The input i cannot have a logical value. • Does not accept vector inputs. • Inputs must be constants. • Uses single-precision arithmetic to produce single-precision results. comm.ACPR Communications “System Objects in MATLAB Code Generation” System Toolbox comm.AGC Communications “System Objects in MATLAB Code Generation” System Toolbox comm.AlgebraicDeinterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.APPDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.AWGNChannel Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BarkerCode Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BCHDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BCHEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BinarySymmetricChannel Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BlockDeinterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BlockInterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BPSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.BPSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox 4-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations comm.CCDF Communications “System Objects in MATLAB Code Generation” System Toolbox comm.ConstellationDiagram Communications “System Objects in MATLAB Code Generation” System Toolbox comm.ConvolutionalDeinterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.ConvolutionalEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.ConvolutionalInterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.CPFSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.CPFSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.CPMCarrierPhaseSynchronizer Communications “System Objects in MATLAB Code Generation” System Toolbox comm.CPMDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.CPMModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.CRCDetector Communications “System Objects in MATLAB Code Generation” System Toolbox comm.CRCGenerator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DBPSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DBPSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.Descrambler Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DifferentialDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox 4-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations comm.DifferentialEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DiscreteTimeVCO Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DPSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DPSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DQPSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.DQPSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.EarlyLateGateTimingSynchronizer Communications “System Objects in MATLAB Code Generation” System Toolbox comm.ErrorRate Communications “System Objects in MATLAB Code Generation” System Toolbox comm.EVM Communications “System Objects in MATLAB Code Generation” System Toolbox comm.FSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.FSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GardnerTimingSynchronizer Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GeneralQAMDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GeneralQAMModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GeneralQAMTCMDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GeneralQAMTCMModulator Communications “System Objects in MATLAB Code Generation” System Toolbox 4-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations comm.GMSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GMSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GMSKTimingSynchronizer Communications “System Objects in MATLAB Code Generation” System Toolbox comm.GoldSequence Communications “System Objects in MATLAB Code Generation” System Toolbox comm.HadamardCode Communications “System Objects in MATLAB Code Generation” System Toolbox comm.HDLCRCDetector Communications “System Objects in MATLAB Code Generation” System Toolbox comm.HDLCRCGenerator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.HDLRSDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.HDLRSEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.HelicalDeinterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.HelicalInterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.IntegrateAndDumpFilter Communications “System Objects in MATLAB Code Generation” System Toolbox comm.IQImbalanceCompensator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.KasamiSequence Communications “System Objects in MATLAB Code Generation” System Toolbox comm.LDPCDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.LDPCEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox 4-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations comm.LTEMIMOChannel Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MatrixDeinterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MatrixHelicalScanDeinterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MatrixHelicalScanInterLeaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MatrixInterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MemorylessNonlinearity Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MER Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MIMOChannel Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MLSEEqualizer Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MSKTimingSynchronizer Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MuellerMullerTimingSynchronizer Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MultiplexedDeinterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.MultiplexedInterleaver Communications “System Objects in MATLAB Code Generation” System Toolbox comm.OFDMDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox 4-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations comm.OFDMModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.OSTBCCombiner Communications “System Objects in MATLAB Code Generation” System Toolbox comm.OSTBCEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.OQPSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.OQPSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PAMDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PAMModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PhaseRequencyOffset Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PhaseNoise Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PNSequence Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PSKCoarseFrequency-Communications “System Objects in MATLAB Code Generation” System Toolbox Estimator comm.PSKCoarseFrequence-Communications “System Objects in MATLAB Code Generation” System Toolbox Estimator comm.PSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PSKTCMDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.PSKTCMModulator Communications “System Objects in MATLAB Code Generation” System Toolbox 4-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations comm.QAMCoarseFrequency-Communications “System Objects in MATLAB Code Generation” System Toolbox Estimator comm.QPSKDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.QPSKModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RaisedCosineReceiveFilter Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RaisedCosineTransmitFilter Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RayleighChannel Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RectangularQAMDemodulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RectangularModulator Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RectangularQAMTCM- Communications “System Objects in MATLAB Code Generation” System Toolbox Demodulator comm.RectangularQAMTCM- Communications “System Objects in MATLAB Code Generation” System Toolbox Modulator comm.RicianChannel Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RSDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.RSEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.Scrambler Communications “System Objects in MATLAB Code Generation” System Toolbox comm.SphereDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.ThermalNoise Communications “System Objects in MATLAB Code Generation” System Toolbox 4-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations comm.TurboDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.TurboEncoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.ViterbiDecoder Communications “System Objects in MATLAB Code Generation” System Toolbox comm.WalshCode Communications “System Objects in MATLAB Code Generation” System Toolbox compan MATLAB — complex MATLAB — complex Fixed-Point Designer — computer MATLAB • Information about the computer on which the code generation software is running. • Use only when the code generation target is S-function (Simulation) or MEX-function. cond MATLAB — conj MATLAB — conj Fixed-Point Designer — conndef Image Processing All input arguments must be compile-time Toolbox constants. continue MATLAB — conv MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations conv Fixed-Point Designer • 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 variablesized signals is computed using the SumMode property of the governing fimath. • In MATLAB, the output for variablesized 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 MATLAB — convergent Fixed-Point Designer — convn MATLAB — cordicabs Fixed-Point Designer • Variable-size signals are not supported. cordicangle Fixed-Point Designer • Variable-size signals are not supported. cordicatan2 Fixed-Point Designer • Variable-size signals are not supported. cordiccart2pol Fixed-Point Designer • Variable-size signals are not supported. cordiccexp Fixed-Point Designer • Variable-size signals are not supported. 4-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations cordiccos Fixed-Point Designer • Variable-size signals are not supported. cordicpol2cart Fixed-Point Designer • Variable-size signals are not supported. cordicrotate Fixed-Point Designer • Variable-size signals are not supported. cordicsin Fixed-Point Designer • Variable-size signals are not supported. cordicsincos Fixed-Point Designer • Variable-size signals are not supported. cornerPoints Computer Vision Compile-time constant input: No restriction System Toolbox Supports MATLAB Function block: No To index locations with this object, use the syntax: points.Location(idx,:), for points object. See visionRecovertformCodeGeneration_kernel.m, which is used in the “Introduction to Code Generation with Feature Matching and Registration” example. corrcoef MATLAB • Row-vector input is only supported when the first two inputs are vectors and nonscalar. cos MATLAB — cos Fixed-Point Designer — cosd MATLAB — cosh MATLAB — cot MATLAB — cotd MATLAB • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. coth MATLAB — 4-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations cov MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” cross MATLAB • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” csc MATLAB — cscd MATLAB • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. csch MATLAB — ctranspose MATLAB — ctranspose Fixed-Point Designer — cumprod MATLAB • Does not support logical inputs. Cast input to double first. • Does not support the direction argument. cumsum MATLAB • Does not support logical inputs. Cast input to double first. • Does not support the direction argument. cumtrapz MATLAB — db2pow Signal Processing — Toolbox 4-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations dct Signal Processing • Code generation for this function requires the Toolbox DSP System Toolbox software. • 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 “Specify Constant Inputs at the Command Line”. de2bi Communications — System Toolbox deal MATLAB — deblank MATLAB • Supports only inputs from the char class. • Input values must be in the range 0-127. dec2bin MATLAB • If input d is double, d must be less than 2^52. • If input d is single, d must be less than 2^23. • Unless you specify input n to be constant and n is large enough that the output has a fixed number of columns regardless of the input values, this function requires variable-sizing support. Without variable-sizing support, n must be at least 52 for double, 23 for single, 16 for char, 32 for int32, 16 for int16, and so on. 4-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations dec2hex MATLAB • If input d is double, d must be less than 2^52. • If input d is single, d must be less than 2^23. • Unless you specify input n to be constant and n is large enough that the output has a fixed number of columns regardless of the input values, this function requires variablesizing support. Without variable-sizing support, n must be at least 13 for double, 6 for single, 4 for char, 8 for int32, 4 for int16, and so on. dechirp Phased Array System Toolbox Does not support variable-size inputs. deconv MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” del2 MATLAB — delayseq Phased Array System Toolbox Does not support variable-size inputs. depressionang Phased Array System Toolbox Does not support variable-size inputs. det MATLAB — detectBRISKFeatures Computer Vision Supports MATLAB Function block: No System Toolbox Generated code for this function uses a precompiled platform-specific shared library. detectFASTFeatures Computer Vision Supports MATLAB Function block: No System Toolbox Generated code for this function uses a precompiled platform-specific shared library. detectHarrisFeatures Computer Vision Compile-time constant input: FilterSize System Toolbox Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. 4-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations detectMinEigenFeatures Computer Vision Compile-time constant input: FilterSize System Toolbox Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. detectMSERFeatures Computer Vision Compile-time constant input: No restriction System Toolbox Supports MATLAB Function block: No For code generation, the function outputs regions.PixelList as an array. The region sizes are defined in regions.Lengths. detectSURFFeatures Computer Vision Compile-time constant input: No restrictions System Toolbox Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. detrend MATLAB • 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]. 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. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations diag MATLAB • If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. • For variable-size inputs that are variablelength vectors (1-by-: or :-by-1), diag: • Treats the input as a vector input. • Returns a matrix with the given vector along the specified diagonal. • For variable-size inputs that are not variablelength vectors, diag: • Treats the input as a matrix. • Does not support inputs that are vectors at run time. • Returns a variable-length vector. If the input is variable-size (:m-by-:n) and has shape 0-by-0 at run time, the output is 0-by-1 not 0-by-0. However, if the input is a constant size 0-by-0, the output is []. • For variable-size inputs that are not variablelength vectors (1-by-: or :-by-1), diag treats the input as a matrix from which to extract a diagonal vector. This behavior occurs even if the input array is a vector at run time. To force diag to build a matrix from variablesize inputs that are not 1-by-: or :-by-1, use: • diag(x(:)) instead of diag(x) • diag(x(:),k) instead of diag(x,k) • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” diag Fixed-Point Designer • If supplied, the index, k, must be a real and scalar integer value that is not a fi object. 4-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations diff MATLAB • If supplied, the arguments representing the number of times to apply diff and the dimension along which to calculate the difference must be constants. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” disparity Computer Vision Compile-time constant input: Method. System Toolbox Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. divide Fixed-Point Designer • Any non-fi input must be constant. 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. dop2speed Phased Array System Toolbox Does not support variable-size inputs. dopsteeringvec Phased Array System Toolbox Does not support variable-size inputs. dot MATLAB — double MATLAB — double Fixed-Point Designer — downsample Signal Processing — Toolbox 4-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations dpss Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. dsp.AdaptiveLatticeFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.AffineProjectionFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.AllpoleFilter DSP System Toolbox • “System Objects in MATLAB Code Generation” • Only the Denominator property is tunable for code generation. dsp.AnalyticSignal DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.ArrayPlot DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.ArrayVectorAdder DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.ArrayVectorDivider DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.ArrayVectorMultiplier DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.ArrayVectorSubtractor DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.AudioFileReader DSP System Toolbox “System Objects in MATLAB Code Generation” 4-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations dsp.AudioRecorder DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.AudioFileWriter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.AudioPlayer DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Autocorrelator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.BiquadFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.BurgAREstimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.BurgSpectrumEstimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.CepstralToLPC DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.CICCompensationDecimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.CICCompensationInterpolator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.CICDecimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.CICInterpolator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Convolver DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Counter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Crosscorrelator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.CrossSpectrumEstimator DSP System Toolbox “System Objects in MATLAB Code Generation” 4-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations dsp.CumulativeProduct DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.CumulativeSum DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.DCBlocker DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.DCT DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Delay DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.DelayLine DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.DigitalDownConverter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.DigitalUpConverter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.DigitalFilter DSP System Toolbox • “System Objects in MATLAB Code Generation” • The SOSMatrix and Scalevalues properties are not supported for code generation. dsp.FarrowRateConverter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FastTransversalFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FFT DSP System Toolbox “System Objects in MATLAB Code Generation” 4-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations dsp.FilterCascade DSP System Toolbox • You cannot generate code directly from dsp.FilterCascade. You can use the generateFilteringCode method to generate a MATLAB function. You can generate C/C++ code from this MATLAB function. “System Objects in MATLAB Code Generation” dsp.FilteredXLMSFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FIRDecimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FIRFilter DSP System Toolbox • “System Objects in MATLAB Code Generation” • Only the Numerator property is tunable for code generation. dsp.FIRHalfbandDecimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FIRHalfbandInterpolator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FIRInterpolator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FIRRateConverter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.FrequencyDomainAdaptiveFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Histogram DSP System Toolbox • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.IDCT DSP System Toolbox “System Objects in MATLAB Code Generation” 4-35 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations dsp.IFFT DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.IIRFilter DSP System Toolbox • Only the Numerator and Denominator properties are tunable for code generation. • “System Objects in MATLAB Code Generation” dsp.Interpolator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.KalmanFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LDLFactor DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LevinsonSolver DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LMSFilter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LowerTriangularSolver DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LPCToAutocorrelation DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LPCToCepstral DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LPCToLSF DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LPCToLSP DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LPCToRC DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LSFToLPC DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.LSPToLPC DSP System Toolbox “System Objects in MATLAB Code Generation” 4-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations dsp.LUFactor DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Maximum DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Mean DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Median DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Minimum DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.NCO DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Normalizer DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.PeakFinder DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.PeakToPeak DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.PeakToRMS DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.PhaseExtractor DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.PhaseUnwrapper DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.RCToAutocorrelation DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.RCToLPC DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.RMS DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.RLSFilter DSP System Toolbox “System Objects in MATLAB Code Generation” 4-37 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations dsp.SampleRateConverter DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.ScalarQuantizerDecoder DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.ScalarQuantizerEncoder DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.SignalSource DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.SineWave DSP System Toolbox • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.SpectrumAnalyzer DSP System Toolbox This System object™ does not generate code. It is automatically declared as an extrinsic variable using the coder.extrinsic function. dsp.SpectrumEstimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.StandardDeviation DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.StateLevels DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.TimeScope DSP System Toolbox This System object does not generate code. It is automatically declared as an extrinsic variable using the coder.extrinsic function. dsp.TransferFunctionEstimator DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.UDPReceiver DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.UDPSender DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.UpperTriangularSolver DSP System Toolbox “System Objects in MATLAB Code Generation” 4-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations dsp.VariableFractionDelay DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.VariableIntegerDelay DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Variance DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.VectorQuantizerDecoder DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.VectorQuantizerEncoder DSP System Toolbox “System Objects in MATLAB Code Generation” dsp.Window DSP System Toolbox • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.ZeroCrossingDetector DSP System Toolbox “System Objects in MATLAB Code Generation” edge Image Processing The method, direction, and sigma arguments Toolbox must be a compile-time constants. In addition, nonprogrammatic syntaxes are not supported. For example, the syntax edge(im), where edge does not return a value but displays an image instead, is not supported. Generated code for this function uses a precompiled platform-specific shared library. effearthradius Phased Array System Toolbox Does not support variable-size inputs. 4-39 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations eig MATLAB • For code generation,QZ algorithm is used in all cases. MATLAB can use different algorithms for different inputs. Consequently, V might represent a different basis of eigenvectors. The eigenvalues in D might not be in the same order as in MATLAB. • With one input, [V,D] = eig(A), the results are 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', and 'nobalance' are not supported for the standard eigenvalue problem. 'chol' is not supported for the symmetric generalized eigenvalue problem. • Outputs are of complex type. • Does not support the option to calculate left eigenvectors. ellip Signal Processing Inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. 4-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations ellipap Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. ellipke MATLAB — ellipord Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. end MATLAB — end Fixed-Point Designer — epipolarLine Computer Vision Compile-time constant input: No restrictions. System Toolbox Supports MATLAB Function block: Yes eps MATLAB — eps Fixed-Point Designer • Supported for scalar fixed-point signals only. eq MATLAB — eq Fixed-Point Designer Not supported for fixed-point signals with different biases. • Supported for scalar, vector, and matrix, fi single and fi double signals. 4-41 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations erf MATLAB — erfc MATLAB — erfcinv MATLAB — erfcx MATLAB — erfinv MATLAB — error MATLAB For standalone code generation, excluded from the generated code. espritdoa Phased Array System Toolbox Does not support variable-size inputs. estimateFundamentalMatrix Computer Vision Compile-time constant input: Method, System Toolbox OutputClass, DistanceType, and ReportRuntimeError. Supports MATLAB Function block: Yes estimateGeometricTransform Computer Vision Compile-time constant input: transformType System Toolbox Supports MATLAB Function block: No estimateUncalibratedRectification Computer Vision Compile-time constant input: transformType System Toolbox Supports MATLAB Function block: No extractFeatures Computer Vision Generates platform-dependent library: Yes for System Toolbox BRISK, FREAK, and SURF methods only. Compile-time constant input: Method Supports MATLAB Function block: Yes for Block method only. Generated code for this function uses a precompiled platform-specific shared library. extractHOGFeatures Computer Vision Compile-time constant input: No System Toolbox Supports MATLAB Function block: No evcdf Statistics Toolbox — evinv Statistics Toolbox — evpdf Statistics Toolbox — 4-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations evrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. evstat Statistics Toolbox — exp MATLAB expcdf Statistics Toolbox — expint MATLAB expinv Statistics Toolbox — expm MATLAB — expm1 MATLAB — exppdf Statistics Toolbox — exprnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: — — • The output is nonscalar. • An input parameter is invalid for the distribution. expstat Statistics Toolbox — eye MATLAB classname must be a built-in MATLAB numeric type. Does not invoke the static eye method for other classes. For example, eye(m, n, 'myclass’) does not invoke myclass.eye(m,n). factor MATLAB • The maximum double precision input is 2^33. • The maximum single precision input is 2^25. • The input n cannot have type int64 or uint64. factorial MATLAB — 4-43 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations false MATLAB • Dimensions must be real, nonnegative, integers. fcdf Statistics Toolbox — fclose MATLAB — feof MATLAB — fft MATLAB • Length of input vector must be a power of 2. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” fft2 MATLAB • Length of input matrix dimensions must each be a power of 2. fftn MATLAB • Length of input matrix dimensions must each be a power of 2. fftshift MATLAB — fi Fixed-Point Designer • Use to create a fixed-point constant or variable. • The default constructor syntax without input arguments is not supported. • The rand 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...). • If the input value is not known at compile time, you must provide complete numerictype information. • All properties related to data type must be constant for code generation. • numerictype object information must be available for non-fixed-point Simulink inputs. 4-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations filter MATLAB • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” filter Fixed-Point Designer • Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. filter2 MATLAB — filtfilt Signal Processing Filter coefficients must be constants. Toolbox 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 “Specify Constant Inputs at the Command Line”. fimath Fixed-Point Designer • 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. • If the ProductMode property of the fimath object is set to anything other than FullPrecision, the ProductWordLength and ProductFractionLength properties must be constant. • If the SumMode property of the fimath object is set to anything other than FullPrecision, the SumWordLength and SumFractionLength properties must be constant. 4-45 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations find MATLAB • 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. findpeaks Signal Processing — Toolbox finv Statistics Toolbox — fir1 Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. 4-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations fir2 Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. firceqrip DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. fircls Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. fircls1 Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. 4-47 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations fireqint DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. firgr DSP System Toolbox • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. firhalfband DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. firlpnorm DSP System Toolbox • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. firls Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. firminphase DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. firnyquist DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. 4-48 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations firpr2chfb DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. firpm Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. firpmord Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. fitgeotrans Image Processing The transformtype argument must be Toolbox a compile-time constant. The function supports the following transformation types: 'nonreflectivesimilarity', 'similarity', 'affine', or 'projective'. fix MATLAB — fix Fixed-Point Designer — fixed.Quantizer Fixed-Point Designer — 4-49 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations flattopwin Signal Processing All inputs must be constants. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. flintmax MATLAB — flip MATLAB — flip Fixed-Point Designer The dimensions argument must be a built-in type; it cannot be a fi object. flipdim MATLAB Note: flipdim will be removed in a future release. Use flip instead. fliplr MATLAB — fliplr Fixed-Point Designer — flipud MATLAB — flipud Fixed-Point Designer — floor MATLAB — floor Fixed-Point Designer — fminsearch MATLAB • Ignores the Display option. Does not print status information during execution. Test the exitflag output for the exit condition. • The output structure does not include the algorithm or message fields. • Ignores the OutputFcn and PlotFcns options. 4-50 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations fopen MATLAB • Does not support: • machineformat, encoding, or fileID inputs • message output • fopen('all') • If you disable extrinsic calls, you cannot return fileIDs created with fopen to MATLAB or extrinsic functions. You can use such fileIDs only internally. • When generating C/C++ executables, static libraries, or dynamic libraries, you can open up to 20 files. • The generated code does not report errors from invalid file identifiers. Write your own file open error handling in your MATLAB code. Test whether fopen returns -1, which indicates that the file open failed. For example: ... fid = fopen(filename, 'r'); if fid == -1 % fopen failed else % fopen successful, okay to call fread A = fread(fid); ... • The behavior of the generated code for fread is compiler-dependent if you: 1 Open a file using fopen with a permission of a+. 2 Read the file using fread before calling an I/O function, such as fseek or 4-51 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations frewind, that sets the file position indicator. for MATLAB — for Fixed-Point Designer — fpdf Statistics Toolbox — 4-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations fprintf MATLAB • Does not support: • b and t subtypes on %u, %o %x, and %X formats. • $ flag for reusing input arguments. • printing arrays. • There is no automatic casting. Input arguments must match their format types for predictable results. • Escaped characters are limited to the decimal range of 0–127. • A call to fprintf with fileID equal to 1 or 2 becomes printf in the generated C/C++ code in the following cases: • The fprintf call is inside a parfor loop. • Extrinsic calls are disabled. • When the MATLAB behavior differs from the C compiler behavior, fprintf matches the C compiler behavior in the following cases: • The format specifier has a corresponding C format specifier, for example, %e or %E. • The fprintf call is inside a parfor loop. • Extrinsic calls are disabled. • When you call fprintf with the format specifier %s, do not put a null character in the middle of the input string. Use fprintf(fid, '%c', char(0)) to write a null character. • When you call fprintf with an integer format specifier, the type of the integer argument must be a type that the target hardware can represent as a native C type. For example, if you call fprintf('%d', 4-53 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations int64(n)), the target hardware must have a native C type that supports a 64-bit integer. 4-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations fread MATLAB • precision must be a constant. • The source and output that precision specifies cannot have values long, ulong, unsigned long, bitN, or ubitN. • You cannot use the machineformat input. • If the source or output that precision specifies is a C type, for example, int, the target and production sizes for that type must: • Match. • Map directly to a MATLAB type. • The source type that precision specifies must map directly to a C type on the target hardware. • If the fread call reads the entire file, all of the data must fit in the largest array available for code generation. • If sizeA is not constant or contains a nonfinite element, then dynamic memory allocation is required. • Treats a char value for source or output as a signed 8-bit integer. Use values between 0 and 127 only. • The generated code does not report file read errors. Write your own file read error handling in your MATLAB code. Test that the number of bytes read matches the number of bytes that you requested. For example: ... N = 100; [vals, numRead] = fread(fid, N, '*double'); if numRead ~= N % fewer elements read than expected 4-55 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations end ... freqspace MATLAB — freqz Signal Processing When called with no output arguments, and Toolbox without a semicolon at the end, freqz returns the complex frequency response of the input filter, evaluated at 512 points. If the semicolon is added, the function produces a plot of the magnitude and phase response of the filter. See “freqz With No Output Arguments”. frewind MATLAB — frnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. fspecial Image Processing All inputs must be constants at compilation Toolbox time. Expressions or variables are allowed if their values do not change. fspl Phased Array System Toolbox fstat Statistics Toolbox — full MATLAB — fzero MATLAB • The first argument must be a function handle. Does not support structure, inline function, or string inputs for the first argument. Does not support variable-size inputs. • Supports up to three output arguments. Does not support the fourth output argument (the output structure). 4-56 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations gain2aperture Phased Array System Toolbox Does not support variable-size inputs. gamcdf Statistics Toolbox — gaminv Statistics Toolbox — gamma MATLAB — gammainc MATLAB Output is always complex. gammaincinv MATLAB Output is always complex. gammaln MATLAB — gampdf Statistics Toolbox — gamrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. gamstat Statistics Toolbox — gausswin Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. gcd MATLAB — ge MATLAB — ge Fixed-Point Designer • Not supported for fixed-point signals with different biases. geocdf Statistics Toolbox — geoinv Statistics Toolbox — 4-57 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations geomean Statistics Toolbox — geopdf Statistics Toolbox — geornd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. geostat Statistics Toolbox — get Fixed-Point Designer • The syntax structure = get(o) is not supported. getlsb Fixed-Point Designer — getmsb Fixed-Point Designer — getrangefromclass Image Processing — Toolbox gevcdf Statistics Toolbox — gevinv Statistics Toolbox — gevpdf Statistics Toolbox — gevrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. gevstat Statistics Toolbox — global2localcoord Phased Array System Toolbox gpcdf Statistics Toolbox — gpinv Statistics Toolbox — gppdf Statistics Toolbox — Does not support variable-size inputs. 4-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations gprnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. gpstat Statistics Toolbox — gradient MATLAB — grazingang Phased Array System Toolbox Does not support variable-size inputs. gt MATLAB — gt Fixed-Point Designer • Not supported for fixed-point signals with different biases. hadamard MATLAB — hamming Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. hankel MATLAB — 4-59 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations hann Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. harmmean Statistics Toolbox — hdl.RAM MATLAB — hex2dec MATLAB — hex2num MATLAB • For n = hex2num(S), size(S,2) <= length(num2hex(0)) hilb MATLAB — hist MATLAB • 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. • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” histeq Image Processing All the syntaxes that include indexed images are Toolbox not supported. This includes all syntaxes that accept map as input and return newmap. Generated code for this function uses a precompiled “platform-specific shared library”. 4-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations horizonrange Phased Array System Toolbox Does not support variable-size inputs. horzcat Fixed-Point Designer — hygecdf Statistics Toolbox — hygeinv Statistics Toolbox — hygepdf Statistics Toolbox — hygernd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. hygestat Statistics Toolbox — hypot MATLAB icdf Statistics Toolbox — idct Signal Processing • Code generation for this function requires the Toolbox DSP System Toolbox software. — • 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 “Specify Constant Inputs at the Command Line”. if, elseif, else MATLAB — 4-61 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations idivide MATLAB • For efficient generated code, MATLAB rules for divide by zero are supported only for the 'round' option. ifft MATLAB • Length of input vector must be a power of 2. • Output of ifft block is complex. • Does not support the 'symmetric' option. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” ifft2 MATLAB • Length of input matrix dimensions must each be a power of 2. • Does not support the 'symmetric' option. ifftn MATLAB • Length of input matrix dimensions must each be a power of 2. • Does not support the 'symmetric' option. ifftshift MATLAB — ifir DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. iircomb DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. iirgrpdelay DSP System Toolbox • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirlpnorm DSP System Toolbox • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. 4-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations iirlpnormc DSP System Toolbox • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirnotch DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. iirpeak DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. im2double MATLAB — im2int16 Image Processing Generated code for this function uses a Toolbox precompiled platform-specific shared library. im2single Image Processing — Toolbox im2uint8 Image Processing Generated code for this function uses a Toolbox precompiled platform-specific shared library. im2uint16 Image Processing Generated code for this function uses a Toolbox precompiled platform-specific shared library. imadjust Image Processing Does not support syntaxes that include indexed Toolbox images. This includes all syntaxes that accept map as input and return newmap. Generated code for this function uses a precompiled “platform-specific shared library”. imag MATLAB — imag Fixed-Point Designer — imaq.VideoDevice Image Acquisition Toolbox “Code Generation with VideoDevice System Object” 4-63 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations imbothat Image Processing The input image IM must be either 2-D or 3-D Toolbox image. The structuring element input argument SE must be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imclearborder Image Processing The optional second input argument, conn, must Toolbox be a compile-time constant. Supports only up to 3-D inputs. Generated code for this function uses a precompiled “platform-specific shared library”. imclose Image Processing The input image IM must be either 2-D or 3-D Toolbox image. The structuring element input argument SE must be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imcomplement Image Processing Does not support int64 and uint64 data types. Toolbox imdilate Image Processing The input image IM must be either 2-D or 3Toolbox D image. The SE, PACKOPT, and SHAPE input arguments must be a compile-time constant. The structuring element argument SE must be a single element—arrays of structuring elements are not supported. To obtain the same result as that obtained using an array of structuring elements, call the function sequentially. Generated code for this function uses a precompiled platform-specific shared library. 4-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations imerode Image Processing The input image IM must be either 2-D or 3Toolbox D image. The SE, PACKOPT, and SHAPE input arguments must be a compile-time constant. The structuring element argument SE must be a single element—arrays of structuring elements are not supported. To obtain the same result as that obtained using an array of structuring elements, call the function sequentially. Generated code for this function uses a precompiled platform-specific shared library. imextendedmax Image Processing The optional third input argument, conn, must Toolbox be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imextendedmin Image Processing The optional third input argument, conn, must Toolbox be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. 4-65 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations imfill Image Processing The optional input connectivity, conn and the Toolbox string 'holes' must be compile time constants. Supports only up to 3-D inputs. (No N-D support.) The interactive mode to select points, imfill(BW,0,CONN) is not supported in code generation. locations can be a P-by-1 vector, in which case it contains the linear indices of the starting locations. locations can also be a Pby-ndims(I) matrix, in which case each row contains the array indices of one of the starting locations. Once you select a format at compiletime, you cannot change it at run time. However, the number of points in locations can be varied at run time. Generated code for this function uses a precompiled platform-specific shared library. imfilter Image Processing The input image can be either 2-D or 3-D. The Toolbox value of the input argument, options, must be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imhist Image Processing The optional second input argument, n, must Toolbox be a compile-time constant. In addition, nonprogrammatic syntaxes are not supported. For example, the syntaxes where imhist displays the histogram are not supported. Generated code for this function uses a precompiled platform-specific shared library. 4-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations imhmax Image Processing The optional third input argument, conn, must Toolbox be a compile-time constant Generated code for this function uses a precompiled platform-specific shared library. imhmin Image Processing The optional third input argument, conn, must Toolbox be a compile-time constant Generated code for this function uses a precompiled platform-specific shared library. imlincomb Image Processing The output_class argument must be a Toolbox compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. imopen Image Processing The input image IM must be either 2-D or 3-D Toolbox image. The structuring element input argument SE must be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imquantize Image Processing — Toolbox imreconstruct Image Processing The optional third input argument, conn, must Toolbox be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imref2d Image Processing The XWorldLimits, YWorldLimits and Toolbox ImageSize properties can be set only during object construction. When generating code, you can only specify single objects—arrays of objects are not supported. 4-67 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations imref3d Image Processing The XWorldLimits, YWorldLimits, Toolbox ZWorldLimits and ImageSize properties can be set only during object construction. When generating code, you can only specify single objects—arrays of objects are not supported. imregionalmax Image Processing The optional second input argument, conn, must Toolbox be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imregionalmin Image Processing The optional second input argument, conn, must Toolbox be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imtophat Image Processing The input image IM must be either 2-D or 3-D Toolbox image. The structuring element input argument SE must be a compile-time constant. Generated code for this function uses a precompiled platform-specific shared library. imwarp Image Processing Geometric transformation object input, tform, Toolbox must be either affine2d or projective2d. Additionally, the interpolation method and optional parameter names must be string constants. Generated code for this function uses a precompiled platform-specific shared library. ind2sub MATLAB • The first argument should be a valid size vector. Size vectors for arrays with more than intmax elements are not supported. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” inf MATLAB • Dimensions must be real, nonnegative, integers. 4-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations insertMarker Computer Vision Compile-time constant input: marker System Toolbox Supports MATLAB Function block: Yes insertShape Computer Vision Compile-time constant input: shape and System Toolbox SmoothEdges Supports MATLAB Function block: Yes int8, int16, int32, int64 MATLAB No integer overflow detection for int64 in MEX or MATLAB Function block simulation on Windows 32-bit platforms. int8, int16, int32, int64 Fixed-Point Designer — integralImage Computer Vision Supports MATLAB Function block: Yes System Toolbox interp1 MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” interp2 MATLAB • Xq and Yq must be the same size. Use meshgrid to evaluate on a grid. • For best results, provide X and Y as vectors. • For the 'cubic' method, reports an error if the grid does not have uniform spacing. In this case, use the 'spline' method. • For best results when you use the 'spline' method: • Use meshgrid to create the inputs Xq and Yq. • Use a small number of interpolation points relative to the dimensions of V. Interpolating over a large set of scattered points can be inefficient. 4-69 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations interp3 MATLAB • Xq, Yq, and Zq must be the same size. Use meshgrid to evaluate on a grid. • For best results, provide X, Y, and Z as vectors. • For the 'cubic' method, reports an error if the grid does not have uniform spacing. In this case, use the 'spline' method. • For best results when you use the 'spline' method: • Use meshgrid to create the inputs Xq, Yq, and Zq. • Use a small number of interpolation points relative to the dimensions of V. Interpolating over a large set of scattered points can be inefficient. 4-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations intersect MATLAB • When you do not specify the 'rows' option: • Inputs A and B must be vectors. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example, zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0by-0. • When you specify both the 'legacy' option and the 'rows' option, the outputs ia and ib are 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. • When the setOrder is 'sorted' or when you specify the 'legacy' option, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). 4-71 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations intfilt Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. intlut Image Processing Generated code for this function uses a Toolbox precompiled “platform-specific shared library”. intmax MATLAB — intmin MATLAB — inv MATLAB Singular matrix inputs can produce nonfinite values that differ from MATLAB results. invhilb MATLAB — ipermute MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” ipermute Fixed-Point Designer — iptcheckconn Image Processing All input arguments must be compile-time Toolbox constants. iptcheckmap Image Processing — Toolbox iqcoef2imbal Communications — System Toolbox iqimbal2coef Communications — System Toolbox iqr Statistics Toolbox — isa MATLAB — iscell MATLAB — 4-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations ischar MATLAB — iscolumn MATLAB — iscolumn Fixed-Point Designer — isdeployed MATLAB Compiler • Returns true and false as appropriate for MEX and SIM targets • Returns false for other targets isempty MATLAB — isempty Fixed-Point Designer — isEpipoleInImage Computer Vision Compile-time constant input: No restrictions. System Toolbox Supports MATLAB Function block: Yes isequal MATLAB — isequal Fixed-Point Designer — isequaln MATLAB — isfi Fixed-Point Designer — isfield MATLAB • Does not support cell input for second argument isfimath Fixed-Point Designer — isfimathlocal Fixed-Point Designer — isfinite MATLAB — isfinite Fixed-Point Designer — isfloat MATLAB — ishermitian MATLAB — isinf MATLAB — 4-73 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations isinf Fixed-Point Designer — isinteger MATLAB — isletter MATLAB • Input values from the char class must be in the range 0-127 islogical MATLAB — ismac MATLAB • Returns true or false based on the MATLAB version used for code generation. • Use only when the code generation target is S-function (Simulation) or MEX-function. ismatrix MATLAB — ismcc MATLAB Compiler • Returns true and false as appropriate for MEX and SIM targets. • Returns false for other targets. ismember MATLAB • The second input, B, must be sorted in ascending order. • Complex inputs must be single or double. isnan MATLAB — isnan Fixed-Point Designer — isnumeric MATLAB — isnumeric Fixed-Point Designer — isnumerictype Fixed-Point Designer — isobject MATLAB — ispc MATLAB • Returns true or false based on the MATLAB version you use for code generation. • Use only when the code generation target is S-function (Simulation) or MEX-function. 4-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations isprime MATLAB • The maximum double precision input is 2^33. • The maximum single precision input is 2^25. • The input X cannot have type int64 or uint64. isreal MATLAB — isreal Fixed-Point Designer — isrow MATLAB — isrow Fixed-Point Designer — isscalar MATLAB — isscalar Fixed-Point Designer — issigned Fixed-Point Designer — issorted MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” isspace MATLAB • Input values from the char class must be in the range 0–127. issparse MATLAB — isstrprop MATLAB • Supports only inputs from char and integer classes. • Input values must be in the range 0-127. isstruct MATLAB — issymmetric MATLAB — istrellis Communications — System Toolbox 4-75 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations isunix MATLAB • Returns true or false based on the MATLAB version used for code generation. • Use only when the code generation target is S-function (Simulation) or MEX-function. isvector MATLAB — isvector Fixed-Point Designer — kaiser Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. kaiserord Signal Processing — Toolbox kron MATLAB kurtosis Statistics Toolbox — — 4-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations label2rgb Image Processing Referring to the standard syntax: Toolbox 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'. lcm MATLAB — lcmvweights Phased Array System Toolbox Does not support variable-size inputs. ldivide MATLAB — le MATLAB — le Fixed-Point Designer • Not supported for fixed-point signals with different biases. length MATLAB — length Fixed-Point Designer — 4-77 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations levinson Signal Processing • Code generation for this function requires the Toolbox DSP System Toolbox software. • 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 “Specify Constant Inputs at the Command Line”. lineToBorderPoints Computer Vision Compile-time constant input: No restrictions. System Toolbox Supports MATLAB Function block: Yes 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 Other options are equivalent to using mldivide. linspace MATLAB — 4-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations load MATLAB • Use only when generating MEX or code for Simulink simulation. To load compile-time constants, use coder.load. • Does not support use of the function without assignment to a structure or array. For example, use S = load(filename), not load(filename). • The output S must be the name of a structure or array without any subscripting. For example, S[i] = load('myFile.mat') is not allowed. • Arguments to load must be compile-time constant strings. • Does not support loading objects. • If the MAT-file contains unsupported constructs, use load(filename,variables) to load only the supported constructs. • You cannot use save in a function intended for code generation. The code generation software does not support the save function. Furthermore, you cannot use coder.extrinsic with save. Prior to generating code, you can use save to save the workspace data to a MAT-file. You must use coder.varsize to explicitly declare variable-size data loaded using the load function. local2globalcoord Phased Array System Toolbox Does not support variable-size inputs. 4-79 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and 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). log2 MATLAB — log10 MATLAB — log1p MATLAB — logical MATLAB — logical Fixed-Point Designer — logncdf Statistics Toolbox — logninv Statistics Toolbox — lognpdf Statistics Toolbox — lognrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. lognstat Statistics Toolbox — logspace MATLAB — lower MATLAB • Supports only char inputs. • Input values must be in the range 0-127. lowerbound Fixed-Point Designer — lsb Fixed-Point Designer • Supported for scalar fixed-point signals only. MATLAB — lt • Supported for scalar, vector, and matrix, fi single and double signals. 4-80 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations lteZadoffChuSeq Communications — System Toolbox lt Fixed-Point Designer • Not supported for fixed-point signals with different biases. lu MATLAB — mad Statistics Toolbox Input dim cannot be empty. magic MATLAB matchFeatures Computer Vision Generates platform-dependent library: Yes for System Toolbox MATLAB host. The function generates portable C code for non-host target. Compile-time constant input: Method and Metric. Supports MATLAB Function block: Yes Generated code for this function uses a precompiled platform-specific shared library. max MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” max Fixed-Point Designer — maxflat Signal Processing Inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. mdltest Phased Array System Toolbox Does not support variable-size inputs. 4-81 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations mean MATLAB • Does not support the 'native' output class option for integer types. • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” mean Fixed-Point Designer N/A mean2 Image Processing — Toolbox medfilt2 Image Processing The padopt argument must be a compile-time Toolbox constant. Generated code for this function uses a precompiled “platform-specific shared library”. median MATLAB • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” median Fixed-Point Designer — meshgrid MATLAB — mfilename MATLAB — min MATLAB • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” min Fixed-Point Designer — minus MATLAB — minus Fixed-Point Designer • Any non-fi input must be constant. Its value must be known at compile time so that it can be cast to a fi object. 4-82 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations mkpp MATLAB • The output structure pp differs from the pp structure in MATLAB. In MATLAB, ppval cannot use the pp structure from the code generation software. For code generation, ppval cannot use a pp structure created by MATLAB. unmkpp can use a MATLAB pp structure for code generation. To create a MATLAB pp structure from a pp structure created by the code generation software: • In code generation, use unmkpp to return the piecewise polynomial details to MATLAB. • In MATLAB, use mkpp to create the pp structure. • If you do not provide d, then coefs must be two-dimensional and have a fixed number of columns. In this case, the number of columns is the order. • To define a piecewise constant polynomial, coefs must be a column vector or d must have at least two elements. • If you provide d and d is 1, d must be a constant. Otherwise, if the input to ppval is nonscalar, the shape of the output of ppval can differ from ppval in MATLAB. • If you provide d, it must have a fixed length. One of the following sets of statements must be true: 1 Suppose that m = length(d) and npieces = length(breaks) - 1. size(coefs,j) = d(j) size(coefs,m+1) = npieces 4-83 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations size(coefs,m+2) = order j = 1,2,...,m. The dimension m+2 must be fixed length. 2 Suppose that m = length(d) and npieces = length(breaks) - 1. size(coefs,1) = prod(d)*npieces size(coefs,2) = order The second dimension must be fixed length. • If you do not provide d, the following statements must be true: Suppose that m = length(d) and npieces = length(breaks) - 1. size(coefs,1) = prod(d)*npieces size(coefs,2) = order The second dimension must be fixed length. mldivide MATLAB — mnpdf Statistics Toolbox — mod MATLAB • Performs the arithmetic using the output class. Results might not match MATLAB due to differences in rounding errors. If one of the inputs has type int64 or uint64, then both inputs must have the same type. mode MATLAB • Does not support third output argument C (cell array). • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” moment Statistics Toolbox If order is nonintegral and X is real, use moment(complex(X), order). mpower MATLAB — 4-84 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations mpower Fixed-Point Designer • 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 variablesized signals is computed using the SumMode property of the governing fimath. • In MATLAB, the output for variablesized 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 Designer • Code generation in MATLAB does not support the syntax F.mpy(a,b). You must use the syntax mpy(F,a,b). • 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 MATLAB — mrdivide Fixed-Point Designer — 4-85 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations MSERRegions Computer Vision Compile-time constant input: No restrictions. System Toolbox Supports MATLAB Function block: Yes For code generation, you must specify both the pixellist cell array and the length of each array, as the second input. The object outputs, regions.PixelList as an array. The region sizes are defined in regions.Lengths. Generated code for this function uses a precompiled platform-specific shared library. mtimes MATLAB • Multiplication of pure imaginary numbers by non-finite numbers might not match MATLAB. The code generation software does not specialize multiplication by pure imaginary numbers—it does not eliminate calculations with the zero real part. For example, (Inf + 1i)*1i = (Inf*0 – 1*1) + (Inf*1 + 1*0)i = NaN + Infi. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-86 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations mtimes Fixed-Point Designer • 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 variablesized signals is computed using the SumMode property of the governing fimath. • In MATLAB, the output for variablesized 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. multithresh Image Processing — Toolbox mvdrweights Phased Array System Toolbox Does not support variable-size inputs. NaN or nan MATLAB • Dimensions must be real, nonnegative, integers. nancov Statistics Toolbox If the input is variable-size and is [] at run time, returns [] not NaN. nanmax Statistics Toolbox — nanmean Statistics Toolbox — nanmedian Statistics Toolbox — nanmin Statistics Toolbox — 4-87 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations nanstd Statistics Toolbox — nansum Statistics Toolbox — nanvar Statistics Toolbox — nargchk MATLAB • Output structure does not include stack information. Note: nargchk will be removed in a future release. nargin MATLAB — narginchk MATLAB — nargout MATLAB • 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 MATLAB — nbincdf Statistics Toolbox — nbininv Statistics Toolbox — nbinpdf Statistics Toolbox — nbinrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. nbinstat Statistics Toolbox — ncfcdf Statistics Toolbox — ncfinv Statistics Toolbox — 4-88 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations ncfpdf Statistics Toolbox — ncfrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. ncfstat Statistics Toolbox — nchoosek MATLAB • When the first input, x, is a scalar, nchoosek returns a binomial coefficient. In this case, x must be a nonnegative integer. It cannot have type int64 or uint64. • When the first input, x, is a vector, nchoosek treats it as a set. In this case, x can have type int64 or uint64. • The second input, k, cannot have type int64 or uint64. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” nctcdf Statistics Toolbox — nctinv Statistics Toolbox — nctpdf Statistics Toolbox — nctrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. nctstat Statistics Toolbox — ncx2cdf Statistics Toolbox — 4-89 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations ncx2rnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. ncx2stat Statistics Toolbox — ndgrid MATLAB — ndims MATLAB — ndims Fixed-Point Designer — ne MATLAB — ne Fixed-Point Designer • Not supported for fixed-point signals with different biases. nearest Fixed-Point Designer — nextpow2 MATLAB — nnz MATLAB — noisepow Phased Array System Toolbox Does not support variable-size inputs. nonzeros MATLAB — norm MATLAB — normcdf Statistics Toolbox — normest MATLAB norminv Statistics Toolbox — normpdf Statistics Toolbox — — 4-90 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations normrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. normstat Statistics Toolbox — not MATLAB — npwgnthresh Phased Array System Toolbox Does not support variable-size inputs. nthroot MATLAB — null MATLAB • Might return a different basis than MATLAB • Does not support rational basis option (second input) num2hex MATLAB — numberofelements Fixed-Point Designer numberofelements will be removed in a future release. Use numel instead. numel MATLAB — numel Fixed-Point Designer — numerictype Fixed-Point Designer • Fixed-point signals coming into 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 the generated code. • All numerictype object properties related to the data type must be constant. 4-91 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations nuttallwin Signal Processing Inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. ocr Computer Vision Compile-time constant input: TextLayout, System Toolbox Language, and CharacterSet. Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. ocrText Computer Vision Compile-time constant input: No restrictions. System Toolbox Supports MATLAB Function block: No ode23 MATLAB • All odeset option arguments must be constant. • Does not support a constant mass matrix in the options structure. Provide a mass matrix as a function . • You must provide at least the two output arguments T and Y. • Input types must be homogeneous—all double or all single. • Variable-sizing support must be enabled. Requires dynamic memory allocation when tspan has two elements or you use event functions. 4-92 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations ode45 MATLAB • All odeset option arguments must be constant. • Does not support a constant mass matrix in the options structure. Provide a mass matrix as a function . • You must provide at least the two output arguments T and Y. • Input types must be homogeneous—all double or all single. • Variable-sizing support must be enabled. Requires dynamic memory allocation when tspan has two elements or you use event functions. odeget MATLAB The name argument must be constant. odeset MATLAB All inputs must be constant. ones MATLAB • Dimensions must be real, nonnegative integers. • The input optimfun must be a function supported for code generation. optimget MATLAB Input parameter names must be constant. 4-93 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations optimset MATLAB • Does not support the syntax that has no input or output arguments: optimset • Functions specified in the options must be supported for code generation. • The fields of the options structure oldopts must be fixed-size fields. • For code generation, optimization functions ignore the Display option. • Does not support the additional options in an options structure created by the Optimization Toolbox™ optimset function. If an input options structure includes the additional Optimization Toolbox options, the output structure does not include them. ordfilt2 Image Processing The padopt argument must be a compile-time Toolbox constant. Generated code for this function uses a precompiled “platform-specific shared library”. or MATLAB — orth MATLAB • Can return a different basis than MATLAB padarray Image Processing • Support only up to 3-D inputs. Toolbox • Input arguments, padval and direction are expected to be compile-time constants. parfor MATLAB • Treated as a for-loop in a MATLAB Function block or when used with fiaccel. • See the parfor reference page in the MATLAB Coder documentation. • “Generate Code with Parallel for-Loops (parfor)”. 4-94 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations parzenwin Signal Processing Inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. pascal MATLAB — pchip MATLAB • Input x must be strictly increasing. • Does not remove y entries with NaN values. • If you generate code for the pp = pchip(x,y) syntax, you cannot input pp to the ppval function in MATLAB. To create a MATLAB pp structure from a pp structure created by the code generation software: • In code generation, use unmkpp to return the piecewise polynomial details to MATLAB. • In MATLAB, use mkpp to create the pp structure. pdf Statistics Toolbox — permute MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” permute Fixed-Point Designer The dimensions argument must be a built-in type; it cannot be a fi object. phased.ADPCACanceller Phased Array System Toolbox “Code Generation” phased.AngleDopplerResponse Phased Array System Toolbox “Code Generation” 4-95 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations phased.ArrayGain Phased Array System Toolbox • Does not support arrays containing polarized antenna elements, that is, the phased.ShortDipoleAntennaElement or phased.CrossedDipoleAntennaElement antennas. • “Code Generation”. phased.ArrayResponse Phased Array System Toolbox “Code Generation” phased.BarrageJammer Phased Array System Toolbox “Code Generation” phased.BeamscanEstimator Phased Array System Toolbox “Code Generation” phased.BeamscanEstimator2D Phased Array System Toolbox “Code Generation” phased.BeamspaceESPRITEstimator Phased Array System Toolbox “Code Generation”. phased.CFARDetector Phased Array System Toolbox “Code Generation” phased.Collector Phased Array System Toolbox “Code Generation” phased.ConformalArray Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.ConstantGammaClutter Phased Array System Toolbox “Code Generation” phased.CosineAntennaElement Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.CrossedDipoleAntennaElement Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. 4-96 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations phased.CustomAntennaElement Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.CustomMicrophoneElement Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation” phased.DPCACanceller Phased Array System Toolbox “Code Generation” phased.ElementDelay Phased Array System Toolbox “Code Generation” phased.ESPRITEstimator Phased Array System Toolbox “Code Generation” phased.FMCWWaveform Phased Array System Toolbox “Code Generation” phased.FreeSpace Phased Array System Toolbox • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. phased.FrostBeamformer Phased Array System Toolbox • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. phased.IsotropicAntennaElement Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. Phased Array System Toolbox “Code Generation” phased.LinearFMWaveform Phased Array System Toolbox “Code Generation” phased.LCMVBeamformer phased.MatchedFilter Phased Array System Toolbox • The CustomSpectrumWindow property is not supported. • “Code Generation”. 4-97 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations phased.MVDRBeamformer Phased Array System Toolbox “Code Generation” phased.MVDREstimator Phased Array System Toolbox “Code Generation” phased.MVDREstimator2D Phased Array System Toolbox “Code Generation” phased.Omnidirectional- Phased Array System Toolbox MicrophoneElement • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.PartitionedArray Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.PhaseCodedWaveform Phased Array System Toolbox “Code Generation” phased.PhaseShiftBeamformer Phased Array System Toolbox “Code Generation” phased.Platform Phased Array System Toolbox “Code Generation” phased.RadarTarget Phased Array System Toolbox “Code Generation” phased.Radiator Phased Array System Toolbox “Code Generation” phased.RangeDopplerResponse Phased Array System Toolbox • The CustomRangeWindow and the CustomDopplerWindow properties are not supported. • “Code Generation”. phased.RectangularWaveform Phased Array System Toolbox “Code Generation” phased.ReceiverPreamp Phased Array System Toolbox “Code Generation” 4-98 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations phased.ReplicatedSubarray Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. Phased Array System Toolbox “Code Generation” phased.RootWSFEstimator Phased Array System Toolbox “Code Generation” phased.RootMUSICEstimator phased.ShortDipoleAntennaElement Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. Phased Array System Toolbox “Code Generation” phased.StretchProcessor Phased Array System Toolbox “Code Generation” phased.SubbandPhaseShiftBeamformer Phased Array System Toolbox “Code Generation” phased.SteeringVector Phased Array System Toolbox “Code Generation” phased.SteppedFMWaveform Phased Array System Toolbox “Code Generation” phased.SumDifferenceMonopulseTracker Phased Array System Toolbox “Code Generation”. phased.SumDifferenceMonopulseTracker2D Phased Array System Toolbox “Code Generation”. phased.TimeDelayBeamformer Phased Array System Toolbox • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. phased.STAPSMIBeamformer • “Code Generation”. phased.TimeDelayLCMVBeamformer Phased Array System Toolbox • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. 4-99 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations phased.TimeVaryingGain Phased Array System Toolbox “Code Generation”. phased.Transmitter Phased Array System Toolbox “Code Generation”. phased.ULA Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.URA Phased Array System Toolbox • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.WidebandCollector Phased Array System Toolbox • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. phitheta2azel Phased Array System Toolbox Does not support variable-size inputs. phitheta2azelpat Phased Array System Toolbox Does not support variable-size inputs. phitheta2uv Phased Array System Toolbox Does not support variable-size inputs. phitheta2uvpat Phased Array System Toolbox Does not support variable-size inputs. physconst Phased Array System Toolbox Does not support variable-size inputs. pi MATLAB — pinv MATLAB — planerot MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” plus MATLAB — plus Fixed-Point Designer • 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. 4-100 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations poisscdf Statistics Toolbox — poissinv Statistics Toolbox — poisspdf Statistics Toolbox — poissrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. poisstat Statistics Toolbox — pol2cart MATLAB — pol2circpol Phased Array System Toolbox Does not support variable-size inputs. polellip Phased Array System Toolbox Does not support variable-size inputs. polloss Phased Array System Toolbox Does not support variable-size inputs. polratio Phased Array System Toolbox Does not support variable-size inputs. polsignature Phased Array System Toolbox • Does not support variable-size inputs. MATLAB • Does not discard nonfinite input values poly • Supported only when output arguments are specified. • Complex input produces complex output • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” polyarea MATLAB — poly2trellis Communications — System Toolbox polyder MATLAB The output can contain fewer NaNs than the MATLAB output. However, if the input contains a NaN, the output contains at least one NaN. 4-101 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations polyfit MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” polyint MATLAB — polyval MATLAB — polyvalm MATLAB — pow2 Fixed-Point Designer — pow2db Signal Processing — Toolbox power MATLAB • Generates an error during simulation. When both X and Y are real, but power(X,Y) is complex, returns NaN in the generated code. 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. When both X and Y are real, but X .^ Y is complex, returns NaN in generated code. To get the complex result, make the input value X complex by using complex(X). For example, complex(X).^Y. power Fixed-Point Designer • The exponent input, k, must be constant. Its value must be known at compile time. 4-102 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations ppval MATLAB The size of output v does not match MATLAB when both of the following statements are true: • The input x is a variable-size array that is not a variable-length vector. • x becomes a row vector at run time. The code generation software does not remove the singleton dimensions. However, MATLAB might remove singleton dimensions. For example, suppose that x is a :4-by-:5 array (the first dimension is variable size with an upper bound of 4 and the second dimension is variable size with an upper bound of 5). Suppose that ppval(pp,0) returns a 2-by-3 fixed-size array. v has size 2-by-3-by-:4-by-:5. At run time, suppose that, size(x,1) =1 and size (x,2) = 5. In the generated code, the size(v) is [2,3,1,5]. In MATLAB, the size is [2,3,5]. prctile Statistics Toolbox • “Automatic dimension restriction” • If the output Y is a vector, the orientation of Y differs from MATLAB when all of the following are true: • You do not supply the dim input. • X is a variable-size array. • X is not a variable-length vector. • X is a vector at run time. • The orientation of the vector X does not match the orientation of the vector p. In this case, the output Y matches the orientation of X not the orientation of p. 4-103 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations primes MATLAB • The maximum double precision input is 2^32. • The maximum single precision input is 2^24. • The input n cannot have type int64 or uint64. prod MATLAB • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” projective2d Image Processing When generating code, you can only specify Toolbox single objects—arrays of objects are not supported. psi MATLAB — pulsint Phased Array System Toolbox Does not support variable-size inputs. qr MATLAB — quad2d MATLAB • Generates a warning if the size of the internal storage arrays is not large enough. If a warning occurs, a possible workaround is to divide the region of integration into pieces and sum the integrals over each piece. quadgk MATLAB — quantile Statistics Toolbox — quantize Fixed-Point Designer — quatconj Aerospace Toolbox Code generation for this function requires the Aerospace Blockset™ software. quatdivide Aerospace Toolbox Code generation for this function requires the Aerospace Blockset software. quatinv Aerospace Toolbox Code generation for this function requires the Aerospace Blockset software. quatmod Aerospace Toolbox Code generation for this function requires the Aerospace Blockset software. 4-104 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations quatmultiply Aerospace Toolbox Code generation for this function requires the Aerospace Blockset software. quatnorm Aerospace Toolbox Code generation for this function requires the Aerospace Blockset software. quatnormalize Aerospace Toolbox Code generation for this function requires the Aerospace Blockset software. radareqpow Phased Array System Toolbox Does not support variable-size inputs. radareqrng Phased Array System Toolbox Does not support variable-size inputs. radareqsnr Phased Array System Toolbox Does not support variable-size inputs. radarvcd Phased Array System Toolbox Does not support variable-size inputs. radialspeed Phased Array System Toolbox Does not support variable-size inputs. rand MATLAB • classname must be a built-in MATLAB numeric type. Does not invoke the static rand method for other classes. For example, rand(sz,'myclass’) does not invoke myclass.rand(sz). • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” randg Statistics Toolbox — randi MATLAB • classname must be a built-in MATLAB numeric type. Does not invoke the static randi method for other classes. For example, randi(imax,sz,'myclass’) does not invoke myclass.randi(imax,sz). • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-105 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations randn MATLAB • classname must be a built-in MATLAB numeric type. Does not invoke the static randn method for other classes. For example, randn(sz,'myclass’) does not invoke myclass.randn(sz). • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” random Statistics Toolbox — randperm MATLAB — range Fixed-Point Designer — range2beat Phased Array System Toolbox Does not support variable-size inputs. range2bw Phased Array System Toolbox Does not support variable-size inputs. range2time Phased Array System Toolbox Does not support variable-size inputs. rangeangle Phased Array System Toolbox Does not support variable-size inputs. rank MATLAB — raylcdf Statistics Toolbox — raylinv Statistics Toolbox — raylpdf Statistics Toolbox — raylrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. raylstat Statistics Toolbox — rcond MATLAB — 4-106 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations rcosdesign Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. rdcoupling Phased Array System Toolbox Does not support variable-size inputs. rdivide MATLAB — rdivide Fixed-Point Designer — real MATLAB — real Fixed-Point Designer — reallog MATLAB — realmax MATLAB — realmax Fixed-Point Designer — realmin MATLAB — realmin Fixed-Point Designer — realpow MATLAB — realsqrt MATLAB — rectint MATLAB — 4-107 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations rectwin Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. reinterpretcast Fixed-Point Designer — rem MATLAB • Performs the arithmetic using the output class. Results might not match MATLAB due to differences in rounding errors. • If one of the inputs has type int64 or uint64, then both inputs must have the same type. removefimath Fixed-Point Designer — repmat MATLAB — repmat Fixed-Point Designer The dimensions argument must be a built-in type; it cannot be a fi object. resample Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. 4-108 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations rescale Fixed-Point Designer — reshape MATLAB • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” reshape Fixed-Point Designer — return MATLAB — rgb2ycbcr Image Processing — Toolbox rng MATLAB • For library code generation targets, executable code generation targets, and MEX targets with extrinsic calls disabled: • Does not support the 'shuffle' input. • For the generator input, supports 'twister', 'v4', and 'v5normal'. For these targets, the output of s=rng in the generated code differs from the MATLAB output. You cannot return the output of s=rng from the generated code and pass it to rng in MATLAB. • For MEX targets, if extrinsic calls are enabled, you cannot access the data in the structure returned by rng. rocpfa rocsnr rootmusicdoa Phased Array System Toolbox • Does not support variable-size inputs. Phased Array System Toolbox • Does not support variable-size inputs. Phased Array System Toolbox Does not support variable-size inputs. • The NonfluctuatingNoncoherent signal type is not supported. • Does not support the NonfluctuatingNoncoherent signal type. 4-109 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations roots MATLAB • Output is variable size. • Output is complex. • Roots are not always in the same order as MATLAB. • Roots of poorly conditioned polynomials do not always match MATLAB. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” rosser MATLAB — rot90 MATLAB — rot90 Fixed-Point Designer In the syntax rot90(A,k), the argument k must be a built-in type; it cannot be a fi object. rotx Phased Array System Toolbox Does not support variable-size inputs. roty Phased Array System Toolbox Does not support variable-size inputs. rotz Phased Array System Toolbox Does not support variable-size inputs. round MATLAB — round Fixed-Point Designer — rsf2csf MATLAB — schur MATLAB Can return a different Schur decomposition in generated code than in MATLAB. sec MATLAB — secd MATLAB • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. sech MATLAB — 4-110 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations selectStrongestBbox Computer Vision Compile-time constant input: No restriction System Toolbox Supports MATLAB Function block: No sensorcov Phased Array System Toolbox Does not support variable-size inputs. sensorsig Phased Array System Toolbox Does not support variable-size inputs. 4-111 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations setdiff MATLAB • When you do not specify the 'rows' option: • Inputs A and B must be vectors. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • Do not use [] to represent the empty set. Use a 1-by-0 or 0-by-1 input, for example, zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0by-0. • When you specify both the 'legacy' and 'rows' options, the output ia is a column vector. If ia is empty, it is 0-by-1, never 0by-0, even if the output C is 0-by-0. • When the setOrder is 'sorted' or when you specify the 'legacy' option, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). 4-112 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations setfimath Fixed-Point Designer — 4-113 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations setxor MATLAB • When you do not specify the 'rows' option: • Inputs A and B must be vectors with the same orientation. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example , zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0by-0. • When you specify both the 'legacy' option and the 'rows' option, the outputs ia and ib are 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. • When the setOrder is 'sorted' or when you specify the 'legacy' flag, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). 4-114 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations sfi Fixed-Point Designer • All properties related to data type must be constant for code generation. sgolay Signal Processing All inputs must be constant. Expressions or Toolbox 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 “Specify Constant Inputs at the Command Line”. shiftdim MATLAB • Second argument must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” shiftdim Fixed-Point Designer The dimensions argument must be a built-in type; it cannot be a fi object. shnidman Phased Array System Toolbox Does not support variable-size inputs. sign MATLAB — sign Fixed-Point Designer — sin MATLAB — sin Fixed-Point Designer — sind MATLAB — single MATLAB — single Fixed-Point Designer — sinh MATLAB — size MATLAB — 4-115 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations size Fixed-Point Designer — skewness Statistics Toolbox — sort MATLAB If the input is a complex type, sort orders the output according to absolute value. When x is a complex type that has all zero imaginary parts, use sort(real(x)) to compute the sort order for real types. See “Code Generation for Complex Data”. sort Fixed-Point Designer The dimensions argument must be a built-in type; it cannot be a fi object. sortrows MATLAB If the input is a complex type, sortrows orders the output according to absolute value. When x is a complex type that has all zero imaginary parts, use sortrows(real(x)) to compute the sort order for real types. See “Code Generation for Complex Data”. sosfilt Signal Processing — Toolbox speed2dop Phased Array System Toolbox Does not support variable-size inputs. sph2cart MATLAB — sph2cartvec Phased Array System Toolbox Does not support variable-size inputs. 4-116 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations spline MATLAB • Input x must be strictly increasing. • Does not remove Y entries with NaN values. • Does not report an error for infinite endslopes in Y. • If you generate code for the pp = spline(x,Y) syntax, you cannot input pp to the ppval function in MATLAB. To create a MATLAB pp structure from a pp structure created by the code generation software: • In code generation, use unmkpp to return the piecewise polynomial details to MATLAB. • In MATLAB, use mkpp to create the pp structure. spsmooth Phased Array System Toolbox Does not support variable-size inputs. squeeze MATLAB — squeeze Fixed-Point Designer — sqrt 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). sqrt Fixed-Point Designer • Complex and [Slope Bias] inputs error out. sqrtm MATLAB — std MATLAB “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” steervec Phased Array System Toolbox Does not support variable-size inputs. • Negative inputs yield a 0 result. 4-117 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations stokes Phased Array System Toolbox • Does not support variable-size inputs. storedInteger Fixed-Point Designer — storedIntegerToDouble Fixed-Point Designer — str2double MATLAB • Does not support cell arrays. • Supported only when output arguments are specified. • Always returns a complex result. str2func MATLAB String must be constant/known at compile time. strcmp MATLAB — strcmpi MATLAB • Input values from the char class must be in the range 0-127. strel Image Processing Input arguments must be compile-time Toolbox constants. The following methods are not supported for code generation: getsequence, reflect, translate, disp, display, loadobj. When generating code, you can only specify single objects—arrays of objects are not supported. stretchfreq2rng Phased Array System Toolbox stretchlim Image Processing Generated code for this function uses a Toolbox precompiled “platform-specific shared library”. strfind MATLAB Does not support variable-size inputs. • Does not support cell arrays. • If pattern does not exist in str, returns zeros(1,0) not []. To check for an empty return, use isempty. • Inputs must be character row vectors. strjust MATLAB — strncmp MATLAB — 4-118 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations strncmpi MATLAB • Input values from the char class must be in the range 0-127. strrep MATLAB • Does not support cell arrays. • If oldSubstr does not exist in origStr, returns blanks(0). To check for an empty return, use isempty. • Inputs must be character row vectors. strtok MATLAB — strtrim MATLAB • Supports only inputs from the char class. • Input values must be in the range 0-127. struct MATLAB — structfun MATLAB • Does not support the ErrorHandler option. • The number of outputs must be less than or equal to three. sub Fixed-Point Designer Code generation in MATLAB does not support the syntax F.sub(a,b). You must use the syntax sub(F,a,b). sub2ind MATLAB • The first argument should be a valid size vector. Size vectors for arrays with more than intmax elements are not supported. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” subsasgn Fixed-Point Designer — subspace MATLAB — subsref Fixed-Point Designer — sum MATLAB • Specify dim as a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-119 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations sum Fixed-Point Designer • Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. surfacegamma Phased Array System Toolbox Does not support variable-size inputs. surfclutterrcs Phased Array System Toolbox Does not support variable-size inputs. SURFPoints Computer Vision Compile-time constant input: No restrictions. System Toolbox Supports MATLAB Function block: No To index locations with this object, use the syntax: points.Location(idx,:), for points object. See visionRecovertformCodeGeneration_kernel.m, which is used in the “Introduction to Code Generation with Feature Matching and Registration” example. svd MATLAB Uses a different SVD implementation than MATLAB. Because the singular value decomposition is not unique, left and right singular vectors might differ from those computed by MATLAB. swapbytes MATLAB 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. switch, case, otherwise MATLAB • If all case expressions are scalar integer values, generates a C switch statement. At run time, if the switch value is not an integer, generates an error. • When the case expressions contain noninteger or nonscalar values, the code generation software generates C if statements in place of a C switch statement. 4-120 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations systemp Phased Array System Toolbox Does not support variable-size inputs. tan MATLAB — tand MATLAB • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. tanh MATLAB — taylorwin Signal Processing Inputs must be constant Toolbox Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specify Constant Inputs at the Command Line”. tcdf Statistics Toolbox — tf2ca DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. tf2cl DSP System Toolbox All inputs must be constant. Expressions or variables are allowed if their values do not change. time2range Phased Array System Toolbox Does not support variable-size inputs. times MATLAB Multiplication of pure imaginary numbers by non-finite numbers might not match MATLAB. The code generation software does not specialize multiplication by pure imaginary numbers— it does not eliminate calculations with the zero real part. For example, (Inf + 1i)*1i = (Inf*0 – 1*1) + (Inf*1 + 1*0)i = NaN + Infi. 4-121 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations times Fixed-Point Designer • 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. tinv Statistics Toolbox — toeplitz MATLAB tpdf Statistics Toolbox — trace MATLAB — transpose MATLAB — transpose Fixed-Point Designer — trapz MATLAB • If supplied, dim must be a constant. — • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” triang Signal Processing Inputs must be constant Toolbox Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specify Constant Inputs at the Command Line”. tril MATLAB • If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. tril Fixed-Point Designer • If supplied, the index, k, must be a real and scalar integer value that is not a fi object. 4-122 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations triu MATLAB • If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. triu Fixed-Point Designer • If supplied, the index, k, must be a real and scalar integer value that is not a fi object. trnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. true MATLAB • Dimensions must be real, nonnegative, integers. tstat Statistics Toolbox — tukeywin Signal Processing Inputs must be constant. Toolbox Specifying constants To specify a constant input for codegen, use coder.Constant. For more information, see “Specify Constant Inputs at the Command Line”. typecast MATLAB • Value of string input argument type must be lowercase. • When you use typecast with inheritance of input port data types in MATLAB Function blocks, you can receive a size error. To avoid this error, specify the block's input port data types explicitly. • Integer input or result classes must map directly to a C type on the target hardware. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-123 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations ufi Fixed-Point Designer • All properties related to data type must be constant for code generation. uint8, uint16, uint32, uint64 MATLAB No integer overflow detection for int64 in MEX or MATLAB Function block simulation on Windows 32-bit platforms. uint8, uint16, uint32, uint64 Fixed-Point Designer — uminus MATLAB — uminus Fixed-Point Designer — unidcdf Statistics Toolbox — unidinv Statistics Toolbox — unidpdf Statistics Toolbox — unidrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. unidstat Statistics Toolbox — unifcdf Statistics Toolbox — unifinv Statistics Toolbox — unifpdf Statistics Toolbox — unifrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. unifstat Statistics Toolbox — unigrid Phased Array System Toolbox Does not support variable-size inputs. 4-124 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations union MATLAB • When you do not specify the 'rows' option: • Inputs A and B must be vectors with the same orientation. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example , zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0by-0. • When you specify both the 'legacy' option and the 'rows' option, the outputs ia and ib are 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. • When the setOrder is 'sorted' or when you specify the 'legacy' option, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). 4-125 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations unique MATLAB • When you do not specify the'rows' option: • The input A must be a vector. If you specify the 'legacy' option, the input A must be a row vector. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example, zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0by-0. • When you specify both the 'rows' option and the 'legacy'option, outputs ia and ic are column vectors. If these outputs are empty, they are 0-by-1, even if the output C is 0-by-0. • When the setOrder is 'sorted' or when you specify the 'legacy' option, the input A must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. unmkpp MATLAB • pp must be a valid piecewise polynomial structure created by mkpp, spline, or pchip in MATLAB or by the code generation software. • Does not support pp structures created by interp1 in MATLAB. 4-126 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations unwrap MATLAB • Row vector input is only supported when the first two inputs are vectors and nonscalar • Performs arithmetic in the output class. Hence, results might not match MATLAB due to different rounding errors upfirdn Signal Processing • Code generation for this function requires the Toolbox DSP System Toolbox software. • 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 “Specify Constant Inputs at the Command Line”. uplus MATLAB — uplus Fixed-Point Designer — upper MATLAB • Supports only char inputs. • Input values must be in the range 0-127. upperbound Fixed-Point Designer — upsample Signal Processing Either declare input n as constant, or use the Toolbox assert function in the calling function to set upper bounds for n. For example, assert(n<10) uv2azel Phased Array System Toolbox Does not support variable-size inputs. 4-127 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations uv2azelpat Phased Array System Toolbox Does not support variable-size inputs. uv2phitheta Phased Array System Toolbox Does not support variable-size inputs. uv2phithetapat Phased Array System Toolbox Does not support variable-size inputs. val2ind Phased Array System Toolbox Does not support variable-size inputs. vander MATLAB — var MATLAB • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” vertcat Fixed-Point Designer — vision.AlphaBlender Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Autocorrelator Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Autothresholder Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.BlobAnalysis Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.BoundaryTracer Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.CascadeObjectDetector Computer Vision Supports MATLAB Function block: No System Toolbox Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.ChromaResampler Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.ColorSpaceConverter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” 4-128 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations vision.ConnectedComponentLabeler Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Convolver Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.ContrastAdjuster Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Crosscorrelator Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.DemosaicInterpolator Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.DCT Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Deinterlacer Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Deployable Computer Vision Generates code on Windows host only. System Toolbox Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.DeployableVideo- Computer Vision Supports MATLAB Function block: Yes System Toolbox Player Generates code on Linux® and Windows platforms Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.EdgeDetector Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.FFT Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.ForegroundDetector Computer Vision Supports MATLAB Function block: No System Toolbox Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” 4-129 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations vision.GammaCorrector Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.GeometricRotator Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.GeometricScaler Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.GeometricShearer Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.GeometricTransformer Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.GeometricTranslator Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Histogram Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.HistogramBasedTracker Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.HistogramEqualizer vision.HoughLines Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.HoughTransform Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.IDCT Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.IFFT Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.ImageComplementer Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.ImageFilter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.ImageDataTypeConverter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” 4-130 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations vision.ImagePadder Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.KalmanFilter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.LocalMaximaFinder Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.MarkerInserter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Maximum Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Median Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.MedianFilter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Mean Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Minimum Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.MorphologicalClose Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.MorphologicalDilate Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.MorphologicalErode Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.MorphologicalOpen Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.PeopleDetector Computer Vision Supports MATLAB Function block: No System Toolbox Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.PointTracker Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” 4-131 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Product Remarks and Limitations vision.PSNR Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Pyramid Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.ShapeInserter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.StandardDeviation Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.TemplateMatcher Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.TextInserter Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.Variance Computer Vision Supports MATLAB Function block: Yes System Toolbox “System Objects in MATLAB Code Generation” vision.VideoFileReader Computer Vision Supports MATLAB Function block: Yes System Toolbox Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.VideoFileWriter Computer Vision Supports MATLAB Function block: Yes System Toolbox Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” wblcdf Statistics Toolbox — wblinv Statistics Toolbox — wblpdf Statistics Toolbox — wblrnd Statistics Toolbox Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. wblstat Statistics Toolbox — while MATLAB — 4-132 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying constants Name Product Remarks and Limitations wilkinson MATLAB — xcorr Signal Processing — Toolbox xor MATLAB ycbcr2rgb Image Processing — Toolbox yulewalk Signal Processing If specified, the order of recursion must be a Toolbox 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 “Specify Constant Inputs at the Command Line”. zeros MATLAB • Dimensions must be real, nonnegative, integers. zp2tf MATLAB — zscore Statistics Toolbox — 4-133 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Functions and Objects Supported for C and C++ Code Generation — Category List You can generate efficient C and C++ code for a subset of MATLAB built-in functions and toolbox functions, classes, and System objects that you call from MATLAB code. These functions, classes, and System objects are listed by MATLAB category or toolbox category in the following tables. For an alphabetical list of supported functions, classes, and System objects, see “Functions and Objects Supported for C and C++ Code Generation — Alphabetical List”. Note: For more information on code generation for fixed-point algorithms, refer to “Code Acceleration and Code Generation from MATLAB”. In this section... “Aerospace Toolbox” on page 4-136 “Arithmetic Operations in MATLAB” on page 4-136 “Bit-Wise Operations MATLAB” on page 4-137 “Casting in MATLAB” on page 4-138 “Communications System Toolbox” on page 4-138 “Complex Numbers in MATLAB” on page 4-144 “Computer Vision System Toolbox” on page 4-144 “Control Flow in MATLAB” on page 4-153 “Data and File Management in MATLAB” on page 4-154 “Data Types in MATLAB” on page 4-157 “Desktop Environment in MATLAB” on page 4-158 “Discrete Math in MATLAB” on page 4-158 “DSP System Toolbox” on page 4-159 “Error Handling in MATLAB” on page 4-166 “Exponents in MATLAB” on page 4-167 “Filtering and Convolution in MATLAB” on page 4-167 “Fixed-Point Designer” on page 4-168 4-134 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List In this section... “HDL Coder” on page 4-178 “Histograms in MATLAB” on page 4-178 “Image Acquisition Toolbox” on page 4-178 “Image Processing in MATLAB” on page 4-178 “Image Processing Toolbox” on page 4-179 “Input and Output Arguments in MATLAB” on page 4-186 “Interpolation and Computational Geometry in MATLAB” on page 4-187 “Linear Algebra in MATLAB” on page 4-190 “Logical and Bit-Wise Operations in MATLAB” on page 4-191 “MATLAB Compiler” on page 4-191 “Matrices and Arrays in MATLAB” on page 4-192 “Neural Network Toolbox” on page 4-199 “Nonlinear Numerical Methods in MATLAB” on page 4-199 “Numerical Integration and Differentiation in MATLAB” on page 4-199 “Optimization Functions in MATLAB” on page 4-200 “Phased Array System Toolbox” on page 4-201 “Polynomials in MATLAB” on page 4-209 “Programming Utilities in MATLAB” on page 4-209 “Relational Operators in MATLAB” on page 4-209 “Rounding and Remainder Functions in MATLAB” on page 4-210 “Set Operations in MATLAB” on page 4-210 “Signal Processing in MATLAB” on page 4-215 “Signal Processing Toolbox” on page 4-216 “Special Values in MATLAB” on page 4-221 “Specialized Math in MATLAB” on page 4-221 “Statistics in MATLAB” on page 4-222 “Statistics Toolbox” on page 4-222 “String Functions in MATLAB” on page 4-231 “Structures in MATLAB” on page 4-233 4-135 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation In this section... “Trigonometry in MATLAB” on page 4-233 Aerospace Toolbox C and C++ code generation for the following Aerospace Toolbox quaternion functions requires the Aerospace Blockset software. Function Remarks and Limitations quatconj — quatdivide — quatinv — quatmod — quatmultiply — quatnorm — quatnormalize — Arithmetic Operations in MATLAB See “Array vs. Matrix Operations” for detailed descriptions of the following operator equivalent functions. Function Remarks and Limitations ctranspose — idivide • For efficient generated code, MATLAB rules for divide by zero are supported only for the 'round' option. isa — ldivide — minus — mldivide — mpower — 4-136 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations mrdivide — mtimes • Multiplication of pure imaginary numbers by non-finite numbers might not match MATLAB. The code generation software does not specialize multiplication by pure imaginary numbers—it does not eliminate calculations with the zero real part. For example, (Inf + 1i)*1i = (Inf*0 – 1*1) + (Inf*1 + 1*0)i = NaN + Infi. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” plus — power • Generates an error during simulation. When both X and Y are real, but power(X,Y) is complex, returns NaN in the generated code. 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. When both X and Y are real, but X .^ Y is complex, returns NaN in generated code. To get the complex result, make the input value X complex by using complex(X). For example, complex(X).^Y. rdivide — times Multiplication of pure imaginary numbers by non-finite numbers might not match MATLAB. The code generation software does not specialize multiplication by pure imaginary numbers—it does not eliminate calculations with the zero real part. For example, (Inf + 1i)*1i = (Inf*0 – 1*1) + (Inf*1 + 1*0)i = NaN + Infi. transpose — uminus — uplus — Bit-Wise Operations MATLAB Function Remarks and Limitations flintmax — swapbytes 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 nondouble inputs, the input port data types must be specified, not inherited. 4-137 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Casting in MATLAB Function Remarks and Limitations cast — char — class — double — int8, int16, int32, No integer overflow detection for int64 in MEX or MATLAB Function int64 block simulation on Windows 32-bit platforms. logical — single — typecast • Value of string input argument type must be lowercase. • When you use typecast with inheritance of input port data types in MATLAB Function blocks, you can receive a size error. To avoid this error, specify the block's input port data types explicitly. • Integer input or result classes must map directly to a C type on the target hardware. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” uint8, uint16, uint32, uint64 No integer overflow detection for int64 in MEX or MATLAB Function block simulation on Windows 32-bit platforms. Communications System Toolbox C and C++ code generation for the following functions and System objects requires the Communications System Toolbox software. Name Remarks and Limitations Input and Output comm.BarkerCode “System Objects in MATLAB Code Generation” comm.GoldSequence “System Objects in MATLAB Code Generation” comm.HadamardCode “System Objects in MATLAB Code Generation” comm.KasamiSequence “System Objects in MATLAB Code Generation” comm.WalshCode “System Objects in MATLAB Code Generation” 4-138 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations comm.PNSequence “System Objects in MATLAB Code Generation” lteZadoffChuSeq — Signal and Delay Management bi2de — de2bi — Display and Visual Analysis comm.ConstellationDiagram “System Objects in MATLAB Code Generation” dsp.ArrayPlot “System Objects in MATLAB Code Generation” dsp.SpectrumAnalyzer “System Objects in MATLAB Code Generation” dsp.TimeScope “System Objects in MATLAB Code Generation” Source Coding comm.DifferentialDecoder “System Objects in MATLAB Code Generation” comm.DifferentialEncoder “System Objects in MATLAB Code Generation” Cyclic Redundancy Check Coding comm.CRCDetector “System Objects in MATLAB Code Generation” comm.CRCGenerator “System Objects in MATLAB Code Generation” comm.HDLCRCDetector “System Objects in MATLAB Code Generation” comm.HDLCRCGenerator “System Objects in MATLAB Code Generation” BCH Codes comm.BCHDecoder “System Objects in MATLAB Code Generation” comm.BCHEncoder “System Objects in MATLAB Code Generation” Reed-Solomon Codes comm.RSDecoder “System Objects in MATLAB Code Generation” comm.RSEncoder “System Objects in MATLAB Code Generation” comm.HDLRSDecoder “System Objects in MATLAB Code Generation” comm.HDLRSEncoder “System Objects in MATLAB Code Generation” LDPC Codes comm.LDPCDecoder “System Objects in MATLAB Code Generation” 4-139 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations comm.LDPCEncoder “System Objects in MATLAB Code Generation” Convolutional Coding comm.APPDecoder “System Objects in MATLAB Code Generation” comm.ConvolutionalEncoder “System Objects in MATLAB Code Generation” comm.TurboDecoder “System Objects in MATLAB Code Generation” comm.TurboEncoder “System Objects in MATLAB Code Generation” comm.ViterbiDecoder “System Objects in MATLAB Code Generation” istrellis — poly2trellis — Signal Operations comm.Descrambler “System Objects in MATLAB Code Generation” comm.Scrambler “System Objects in MATLAB Code Generation” Interleaving comm.AlgebraicDeinterleaver “System Objects in MATLAB Code Generation” comm.AlgebraicInterleaver “System Objects in MATLAB Code Generation” comm.BlockDeinterleaver “System Objects in MATLAB Code Generation” comm.BlockInterleaver “System Objects in MATLAB Code Generation” comm.ConvolutionalDeinterleaver “System Objects in MATLAB Code Generation” comm.ConvolutionalInterleaver “System Objects in MATLAB Code Generation” comm.HelicalDeinterleaver “System Objects in MATLAB Code Generation” comm.HelicalInterleaver “System Objects in MATLAB Code Generation” comm.MatrixDeinterleaver “System Objects in MATLAB Code Generation” comm.MatrixInterleaver “System Objects in MATLAB Code Generation” comm.MatrixHelicalScanDeinterleaver “System Objects in MATLAB Code Generation” comm.MatrixHelicalScanInterleaver “System Objects in MATLAB Code Generation” comm.MultiplexedDeinterleaver “System Objects in MATLAB Code Generation” comm.MultiplexedInterleaver “System Objects in MATLAB Code Generation” Frequency Modulation 4-140 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations comm.FSKDemodulator “System Objects in MATLAB Code Generation” comm.FSKModulator “System Objects in MATLAB Code Generation” Phase Modulation comm.BPSKDemodulator “System Objects in MATLAB Code Generation” comm.BPSKModulator “System Objects in MATLAB Code Generation” comm.DBPSKDemodulator “System Objects in MATLAB Code Generation” comm.DBPSKModulator “System Objects in MATLAB Code Generation” comm.DPSKDemodulator “System Objects in MATLAB Code Generation” comm.DPSKModulator “System Objects in MATLAB Code Generation” comm.DQPSKDemodulator “System Objects in MATLAB Code Generation” comm.DQPSKModulator “System Objects in MATLAB Code Generation” comm.OQPSKDemodulator “System Objects in MATLAB Code Generation” comm.OQPSKModulator “System Objects in MATLAB Code Generation” comm.PSKDemodulator “System Objects in MATLAB Code Generation” comm.PSKModulator “System Objects in MATLAB Code Generation” comm.QPSKDemodulator “System Objects in MATLAB Code Generation” comm.QPSKModulator “System Objects in MATLAB Code Generation” Amplitude Modulation comm.GeneralQAMDemodulator “System Objects in MATLAB Code Generation” comm.GeneralQAMModulator “System Objects in MATLAB Code Generation” comm.PAMDemodulator “System Objects in MATLAB Code Generation” comm.PAMModulator “System Objects in MATLAB Code Generation” comm.RectangularQAMDemodulator “System Objects in MATLAB Code Generation” comm.RectangularQAMModulator “System Objects in MATLAB Code Generation” Continuous Phase Modulation comm.CPFSKDemodulator “System Objects in MATLAB Code Generation” comm.CPFSKModulator “System Objects in MATLAB Code Generation” comm.CPMDemodulator “System Objects in MATLAB Code Generation” 4-141 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations comm.CPMModulator “System Objects in MATLAB Code Generation” comm.GMSKDemodulator “System Objects in MATLAB Code Generation” comm.GMSKModulator “System Objects in MATLAB Code Generation” comm.MSKDemodulator “System Objects in MATLAB Code Generation” comm.MSKModulator “System Objects in MATLAB Code Generation” Trellis Coded Modulation comm.GeneralQAMTCMDemodulator “System Objects in MATLAB Code Generation” comm.GeneralQAMTCMModulator “System Objects in MATLAB Code Generation” comm.PSKTCMDemodulator “System Objects in MATLAB Code Generation” comm.PSKTCMModulator “System Objects in MATLAB Code Generation” comm.RectangularQAMTCMDemodulator “System Objects in MATLAB Code Generation” comm.RectangularQAMTCMModulator “System Objects in MATLAB Code Generation” Orthogonal Frequency-Division Modulation comm.OFDMDemodulator “System Objects in MATLAB Code Generation” comm.OFDMModulator “System Objects in MATLAB Code Generation” Filtering comm.IntegrateAndDumpFilter “System Objects in MATLAB Code Generation” comm.RaisedCosineReceiveFilter “System Objects in MATLAB Code Generation” comm.RaisedCosineTransmitFilter “System Objects in MATLAB Code Generation” Carrier Phase Synchronization comm.CPMCarrierPhaseSynchronizer “System Objects in MATLAB Code Generation” comm.PSKCarrierPhaseSynchronizer “System Objects in MATLAB Code Generation” Timing Phase Synchronization comm.EarlyLateGateTimingSynchronizer “System Objects in MATLAB Code Generation” comm.GardnerTimingSynchronizer “System Objects in MATLAB Code Generation” comm.GMSKTimingSynchronizer “System Objects in MATLAB Code Generation” comm.MSKTimingSynchronizer “System Objects in MATLAB Code Generation” comm.MuellerMullerTimingSynchronizer “System Objects in MATLAB Code Generation” 4-142 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations Synchronization Utilities “System Objects in MATLAB Code Generation” comm.DiscreteTimeVCO Equalization “System Objects in MATLAB Code Generation” comm.MLSEEqualizer MIMO comm.LTEMIMOChannel “System Objects in MATLAB Code Generation” comm.MIMOChannel “System Objects in MATLAB Code Generation” comm.OSTBCCombiner “System Objects in MATLAB Code Generation” comm.OSTBCEncoder “System Objects in MATLAB Code Generation” comm.SphereDecoder “System Objects in MATLAB Code Generation” Channel Modeling and RF Impairments comm.AGC “System Objects in MATLAB Code Generation” comm.AWGNChannel “System Objects in MATLAB Code Generation” comm.BinarySymmetricChannel “System Objects in MATLAB Code Generation” comm.IQImbalanceCompensator “System Objects in MATLAB Code Generation” comm.LTEMIMOChannel “System Objects in MATLAB Code Generation” comm.MemorylessNonlinearity “System Objects in MATLAB Code Generation” comm.MIMOChannel “System Objects in MATLAB Code Generation” comm.PhaseFrequencyOffset “System Objects in MATLAB Code Generation” comm.PhaseNoise “System Objects in MATLAB Code Generation” comm.RayleighChannel “System Objects in MATLAB Code Generation” comm.RicianChannel “System Objects in MATLAB Code Generation” comm.ThermalNoise “System Objects in MATLAB Code Generation” comm.PSKCoarseFrequencyEstimator “System Objects in MATLAB Code Generation” comm.QAMCoarseFrequencyEstimator “System Objects in MATLAB Code Generation” iqcoef2imbal — iqimbal2coef — Measurements and Analysis 4-143 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations comm.ACPR “System Objects in MATLAB Code Generation” comm.CCDF “System Objects in MATLAB Code Generation” comm.ErrorRate “System Objects in MATLAB Code Generation” comm.EVM “System Objects in MATLAB Code Generation” comm.MER “System Objects in MATLAB Code Generation” Complex Numbers in MATLAB Function Remarks and Limitations complex — conj — imag — isnumeric — isreal — isscalar — real — unwrap • Row vector input is only supported when the first two inputs are vectors and nonscalar • Performs arithmetic in the output class. Hence, results might not match MATLAB due to different rounding errors Computer Vision System Toolbox C and C++ code generation for the following functions and System objects requires the Computer Vision System Toolbox software. Name Remarks and Limitations Feature Detection, Extraction, and Matching BRISKPoints Compile-time constant inputs: No restriction Supports MATLAB Function block: No To index locations with this object, use the syntax: points.Location(idx,:), 4-144 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations for points object. See visionRecovertformCodeGeneration_kernel.m, which is used in the “Introduction to Code Generation with Feature Matching and Registration” example. cornerPoints Compile-time constant input: No restriction Supports MATLAB Function block: No To index locations with this object, use the syntax: points.Location(idx,:), for points object. See visionRecovertformCodeGeneration_kernel.m, which is used in the “Introduction to Code Generation with Feature Matching and Registration” example. detectBRISKFeatures Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. detectFASTFeatures Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. detectHarrisFeatures Compile-time constant input: FilterSize Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. detectMinEigenFeatures Compile-time constant input: FilterSize Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. detectMSERFeatures Compile-time constant input: No restriction Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. For code generation, the function outputs regions.PixelList as an array. The region sizes are defined in regions.Lengths. 4-145 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations detectSURFFeatures Compile-time constant input: No restrictions Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. extractFeatures Generates platform-dependent library: Yes for BRISK, FREAK, and SURF methods only. Compile-time constant input: Method Supports MATLAB Function block: Yes for Block method only. Generated code for this function uses a precompiled platform-specific shared library. extractHOGFeatures Compile-time constant input: No Supports MATLAB Function block: No matchFeatures Generates platform-dependent library: Yes for MATLAB host. Generates portable C code for non-host target. Compile-time constant input: Method and Metric. Supports MATLAB Function block: Yes MSERRegions Compile-time constant input: No restrictions. Supports MATLAB Function block: Yes For code generation, you must specify both the pixellist cell array and the length of each array, as the second input. The object outputs, regions.PixelList as an array. The region sizes are defined in regions.Lengths. Generated code for this function uses a precompiled platform-specific shared library. 4-146 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations SURFPoints Compile-time constant input: No restrictions. Supports MATLAB Function block: No To index locations with this object, use the syntax: points.Location(idx,:), for points object. See visionRecovertformCodeGeneration_kernel.m, which is used in the “Introduction to Code Generation with Feature Matching and Registration” example. vision.BoundaryTracer Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.EdgeDetector Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Image Registration and Geometric Transformations estimateGeometricTransform Compile-time constant input: transformType Supports MATLAB Function block: No vision.GeometricRotator Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.GeometricScaler Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.GeometricShearer Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.GeometricTransformer Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.GeometricTranslator Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Object Detection and Recognition ocr Compile-time constant input: TextLayout, Language, and CharacterSet. Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. 4-147 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations ocrText Compile-time constant input: No restrictions. Supports MATLAB Function block: No vision.PeopleDetector Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.CascadeObjectDetector Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” Tracking and Motion Estimation assignDetectionsToTracks Compile-time constant input: No restriction. Supports MATLAB Function block: Yes vision.BlockMatcher Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ForegroundDetector Supports MATLAB Function block: No Generates platform-dependent library: Yes for MATLAB host. Generates portable C code for non-host target. Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.HistogramBasedTracker Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.KalmanFilter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.OpticalFlow Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.PointTracker Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.TemplateMatcher Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Camera Calibration and Stereo Vision 4-148 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations bboxOverlapRatio Compile-time constant input: No restriction Supports MATLAB Function block: No disparity Compile-time constant input: Method. Supports MATLAB Function block: No Generated code for this function uses a precompiled platform-specific shared library. epipolarline Compile-time constant input: No restrictions. Supports MATLAB Function block: Yes estimateFundamentalMatrix Compile-time constant input: Method, OutputClass, DistanceType, and ReportRuntimeError. Supports MATLAB Function block: Yes estimateUncalibratedRectification Compile-time constant input: transformType Supports MATLAB Function block: No isEpipoleInImage Compile-time constant input: No restrictions. Supports MATLAB Function block: Yes lineToBorderPoints Compile-time constant input: No restrictions. Supports MATLAB Function block: Yes selectStrongestBbox Compile-time constant input: No restriction Supports MATLAB Function block: No Statistics vision.Autocorrelator Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.BlobAnalysis Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Crosscorrelator Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Histogram Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.LocalMaximaFinder Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Maximum Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” 4-149 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations vision.Mean Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Median Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Minimum Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.PSNR Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.StandardDeviation Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Variance Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Morphological Operations vision.ConnectedComponentLabeler Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.MorphologicalBottomHat Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.MorphologicalClose Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.MorphologicalDilate Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.MorphologicalErode Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.MorphologicalOpen Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.MorphologicalTopHat Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Filters, Transforms, and Enhancements integralImage Supports MATLAB Function block: Yes vision.Convolver Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” 4-150 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations vision.ContrastAdjuster Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.DCT Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Deinterlacer Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.EdgeDetector Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.FFT Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.HistogramEqualizer Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.HoughLines Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.HoughTransform Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.IDCT Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.IFFT Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ImageFilter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.MedianFilter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.Pyramid Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Video Loading, Saving, and Streaming vision.DeployableVideoPlayer Supports MATLAB Function block: Yes Generates code on Linux and Windows platforms Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” 4-151 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations vision.VideoFileReader Supports MATLAB Function block: Yes Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” vision.VideoFileWriter Supports MATLAB Function block: Yes Generated code for this function uses a precompiled platform-specific shared library. “System Objects in MATLAB Code Generation” Color Space Formatting and Conversions vision.Autothresholder Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ChromaResampler Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ColorSpaceConverter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.DemosaicInterpolator Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.GammaCorrector Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ImageComplementer Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ImageDataTypeConverter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ImagePadder Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Graphics insertMarker Compile-time constant input: marker Supports MATLAB Function block: Yes insertShape Compile-time constant input: shape and SmoothEdges Supports MATLAB Function block: Yes vision.AlphaBlender Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” 4-152 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations vision.MarkerInserter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.ShapeInserter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” vision.TextInserter Supports MATLAB Function block: Yes “System Objects in MATLAB Code Generation” Control Flow in MATLAB Function Remarks and Limitations break — continue — end — for — if, elseif, else — parfor • Treated as a for-loop in a MATLAB Function block or when used with fiaccel. • See the parfor reference page in the MATLAB Coder documentation. • “Generate Code with Parallel for-Loops (parfor)”. return — switch, case, otherwise • If all case expressions are scalar integer values, generates a C switch statement. At run time, if the switch value is not an integer, generates an error. • When the case expressions contain noninteger or nonscalar values, the code generation software generates C if statements in place of a C switch statement. while — 4-153 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Data and File Management in MATLAB Function Remarks and Limitations computer • Information about the computer on which the code generation software is running. • Use only when the code generation target is S-function (Simulation) or MEX-function. fclose — feof — fopen • Does not support: • machineformat, encoding, or fileID inputs • message output • fopen('all') • If you disable extrinsic calls, you cannot return fileIDs created with fopen to MATLAB or extrinsic functions. You can use such fileIDs only internally. • When generating C/C++ executables, static libraries, or dynamic libraries, you can open up to 20 files. • The generated code does not report errors from invalid file identifiers. Write your own file open error handling in your MATLAB code. Test whether fopen returns -1, which indicates that the file open failed. For example: ... fid = fopen(filename, 'r'); if fid == -1 % fopen failed else % fopen successful, okay to call fread A = fread(fid); ... • The behavior of the generated code for fread is compiler-dependent if you: 1 Open a file using fopen with a permission of a+. 4-154 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations 2 Read the file using fread before calling an I/O function, such as fseek or frewind, that sets the file position indicator. fprintf • Does not support: • b and t subtypes on %u, %o %x, and %X formats. • $ flag for reusing input arguments. • printing arrays. • There is no automatic casting. Input arguments must match their format types for predictable results. • Escaped characters are limited to the decimal range of 0–127. • A call to fprintf with fileID equal to 1 or 2 becomes printf in the generated C/C++ code in the following cases: • The fprintf call is inside a parfor loop. • Extrinsic calls are disabled. • When the MATLAB behavior differs from the C compiler behavior, fprintf matches the C compiler behavior in the following cases: • The format specifier has a corresponding C format specifier, for example, %e or %E. • The fprintf call is inside a parfor loop. • Extrinsic calls are disabled. • When you call fprintf with the format specifier %s, do not put a null character in the middle of the input string. Use fprintf(fid, '%c', char(0)) to write a null character. • When you call fprintf with an integer format specifier, the type of the integer argument must be a type that the target hardware can represent as a native C type. For example, if you call fprintf('%d', int64(n)), the target hardware must have a native C type that supports a 64-bit integer. 4-155 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations fread • precision must be a constant. • The source and output that precision specifies cannot have values long, ulong, unsigned long, bitN, or ubitN. • You cannot use the machineformat input. • If the source or output that precision specifies is a C type, for example, int, the target and production sizes for that type must: • Match. • Map directly to a MATLAB type. • The source type that precision specifies must map directly to a C type on the target hardware. • If the fread call reads the entire file, all of the data must fit in the largest array available for code generation. • If sizeA is not constant or contains a nonfinite element, then dynamic memory allocation is required. • Treats a char value for source or output as a signed 8-bit integer. Use values between 0 and 127 only. • The generated code does not report file read errors. Write your own file read error handling in your MATLAB code. Test that the number of bytes read matches the number of bytes that you requested. For example: ... N = 100; [vals, numRead] = fread(fid, N, '*double'); if numRead ~= N % fewer elements read than expected end ... frewind — 4-156 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations load • Use only when generating MEX or code for Simulink simulation. To load compile-time constants, use coder.load. • Does not support use of the function without assignment to a structure or array. For example, use S = load(filename), not load(filename). • The output S must be the name of a structure or array without any subscripting. For example, S[i] = load('myFile.mat') is not allowed. • Arguments to load must be compile-time constant strings. • Does not support loading objects. • If the MAT-file contains unsupported constructs, use load(filename,variables) to load only the supported constructs. • You cannot use save in a function intended for code generation. The code generation software does not support the save function. Furthermore, you cannot use coder.extrinsic with save. Prior to generating code, you can use save to save the workspace data to a MATfile. You must use coder.varsize to explicitly declare variable-size data loaded using the load function. Data Types in MATLAB Function Remarks and Limitations deal — iscell — isobject — nargchk • Output structure does not include stack information. Note: nargchk will be removed in a future release. narginchk — nargoutchk — 4-157 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations str2func • String must be constant/known at compile time structfun • Does not support the ErrorHandler option. • The number of outputs must be less than or equal to three. Desktop Environment in MATLAB Function Remarks and Limitations ismac • Returns true or false based on the MATLAB version used for code generation. • Use only when the code generation target is S-function (Simulation) or MEX-function. • Returns true or false based on the MATLAB version you use for code generation. ispc • Use only when the code generation target is S-function (Simulation) or MEX-function. • Returns true or false based on the MATLAB version used for code generation. isunix • Use only when the code generation target is S-function (Simulation) or MEX-function. Discrete Math in MATLAB Function Remarks and Limitations factor • The maximum double precision input is 2^33. • The maximum single precision input is 2^25. • The input n cannot have type int64 or uint64. gcd — isprime • The maximum double precision input is 2^33. • The maximum single precision input is 2^25. • The input X cannot have type int64 or uint64. lcm — 4-158 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations nchoosek • When the first input, x, is a scalar, nchoosek returns a binomial coefficient. In this case, x must be a nonnegative integer. It cannot have type int64 or uint64. • When the first input, x, is a vector, nchoosek treats it as a set. In this case, x can have type int64 or uint64. • The second input, k, cannot have type int64 or uint64. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” • The maximum double precision input is 2^32. primes • The maximum single precision input is 2^24. • The input n cannot have type int64 or uint64. DSP System Toolbox C code generation for the following functions and System objects requires the DSP System Toolbox license. Many DSP System Toolbox functions require constant inputs for code generation. See “Define Constant Input Parameters in a Project” and“Specify Constant Inputs at the Command Line”. Name Remarks and Limitations Estimation dsp.BurgAREstimator “System Objects in MATLAB Code Generation” dsp.BurgSpectrumEstimator “System Objects in MATLAB Code Generation” dsp.CepstralToLPC “System Objects in MATLAB Code Generation” dsp.CrossSpectrumEstimator “System Objects in MATLAB Code Generation” dsp.LevinsonSolver “System Objects in MATLAB Code Generation” dsp.LPCToAutocorrelation “System Objects in MATLAB Code Generation” dsp.LPCToCepstral “System Objects in MATLAB Code Generation” dsp.LPCToLSF “System Objects in MATLAB Code Generation” dsp.LPCToLSP “System Objects in MATLAB Code Generation” dsp.LPCToRC “System Objects in MATLAB Code Generation” dsp.LSFToLPC “System Objects in MATLAB Code Generation” 4-159 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations dsp.LSPToLPC “System Objects in MATLAB Code Generation” dsp.RCToAutocorrelation “System Objects in MATLAB Code Generation” dsp.RCToLPC “System Objects in MATLAB Code Generation” dsp.SpectrumEstimator “System Objects in MATLAB Code Generation” dsp.TransferFunctionEstimator “System Objects in MATLAB Code Generation” Filters ca2tf All inputs must be constant. Expressions or variables are allowed if their values do not change. cl2tf All inputs must be constant. Expressions or variables are allowed if their values do not change. dsp.AdaptiveLatticeFilter “System Objects in MATLAB Code Generation” dsp.AffineProjectionFilter “System Objects in MATLAB Code Generation” dsp.AllpoleFilter • “System Objects in MATLAB Code Generation” • Only the Denominator property is tunable for code generation. dsp.BiquadFilter “System Objects in MATLAB Code Generation” dsp.CICCompensationDecimator “System Objects in MATLAB Code Generation” dsp.CICCompensationInterpolator “System Objects in MATLAB Code Generation” dsp.CICDecimator “System Objects in MATLAB Code Generation” dsp.CICInterpolator “System Objects in MATLAB Code Generation” dsp.FarrowRateConverter “System Objects in MATLAB Code Generation” dsp.FastTransversalFilter “System Objects in MATLAB Code Generation” 4-160 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations dsp.FilterCascade • You cannot generate code directly from dsp.FilterCascade. You can use the generateFilteringCode method to generate a MATLAB function. You can generate C/C++ code from this MATLAB function. • “System Objects in MATLAB Code Generation” dsp.FilteredXLMSFilter “System Objects in MATLAB Code Generation” dsp.FIRDecimator “System Objects in MATLAB Code Generation” dsp.FIRFilter • “System Objects in MATLAB Code Generation” • Only the Numerator property is tunable for code generation. dsp.FIRHalfbandDecimator “System Objects in MATLAB Code Generation” dsp.FIRHalfbandInterpolator “System Objects in MATLAB Code Generation” dsp.FIRInterpolator “System Objects in MATLAB Code Generation” dsp.FIRRateConverter “System Objects in MATLAB Code Generation” dsp.FrequencyDomainAdaptiveFilter “System Objects in MATLAB Code Generation” dsp.IIRFilter • Only the Numerator and Denominator properties are tunable for code generation. • “System Objects in MATLAB Code Generation” dsp.KalmanFilter “System Objects in MATLAB Code Generation” dsp.LMSFilter “System Objects in MATLAB Code Generation” dsp.RLSFilter “System Objects in MATLAB Code Generation” dsp.SampleRateConverter “System Objects in MATLAB Code Generation” firceqrip All inputs must be constant. Expressions or variables are allowed if their values do not change. 4-161 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations fireqint All inputs must be constant. Expressions or variables are allowed if their values do not change. firgr • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. firhalfband All inputs must be constant. Expressions or variables are allowed if their values do not change. firlpnorm • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. firminphase All inputs must be constant. Expressions or variables are allowed if their values do not change. firnyquist All inputs must be constant. Expressions or variables are allowed if their values do not change. firpr2chfb All inputs must be constant. Expressions or variables are allowed if their values do not change. ifir All inputs must be constant. Expressions or variables are allowed if their values do not change. iircomb All inputs must be constant. Expressions or variables are allowed if their values do not change. 4-162 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations iirgrpdelay • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirlpnorm • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirlpnormc • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirnotch All inputs must be constant. Expressions or variables are allowed if their values do not change. iirpeak All inputs must be constant. Expressions or variables are allowed if their values do not change. tf2ca All inputs must be constant. Expressions or variables are allowed if their values do not change. tf2cl All inputs must be constant. Expressions or variables are allowed if their values do not change. Math Operations dsp.ArrayVectorAdder “System Objects in MATLAB Code Generation” dsp.ArrayVectorDivider “System Objects in MATLAB Code Generation” dsp.ArrayVectorMultiplier “System Objects in MATLAB Code Generation” dsp.ArrayVectorSubtractor “System Objects in MATLAB Code Generation” 4-163 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations dsp.CumulativeProduct “System Objects in MATLAB Code Generation” dsp.CumulativeSum “System Objects in MATLAB Code Generation” dsp.LDLFactor “System Objects in MATLAB Code Generation” dsp.LevinsonSolver “System Objects in MATLAB Code Generation” dsp.LowerTriangularSolver “System Objects in MATLAB Code Generation” dsp.LUFactor “System Objects in MATLAB Code Generation” dsp.Normalizer “System Objects in MATLAB Code Generation” dsp.UpperTriangularSolver “System Objects in MATLAB Code Generation” Quantizers dsp.ScalarQuantizerDecoder “System Objects in MATLAB Code Generation” dsp.ScalarQuantizerEncoder “System Objects in MATLAB Code Generation” dsp.VectorQuantizerDecoder “System Objects in MATLAB Code Generation” dsp.VectorQuantizerEncoder “System Objects in MATLAB Code Generation” Scopes dsp.SpectrumAnalyzer This System object does not generate code. It is automatically declared as an extrinsic variable using the coder.extrinsic function. dsp.TimeScope This System object does not generate code. It is automatically declared as an extrinsic variable using the coder.extrinsic function. Signal Management dsp.Counter “System Objects in MATLAB Code Generation” dsp.DelayLine “System Objects in MATLAB Code Generation” Signal Operations dsp.Convolver “System Objects in MATLAB Code Generation” dsp.DCBlocker “System Objects in MATLAB Code Generation” dsp.Delay “System Objects in MATLAB Code Generation” dsp.DigitalDownConverter “System Objects in MATLAB Code Generation” dsp.DigitalUpConverter “System Objects in MATLAB Code Generation” 4-164 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations dsp.Interpolator “System Objects in MATLAB Code Generation” dsp.NCO “System Objects in MATLAB Code Generation” dsp.PeakFinder “System Objects in MATLAB Code Generation” dsp.PhaseExtractor “System Objects in MATLAB Code Generation” dsp.PhaseUnwrapper “System Objects in MATLAB Code Generation” dsp.VariableFractionalDelay “System Objects in MATLAB Code Generation” dsp.VariableIntegerDelay “System Objects in MATLAB Code Generation” dsp.Window • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.ZeroCrossingDetector “System Objects in MATLAB Code Generation” Sinks dsp.AudioPlayer “System Objects in MATLAB Code Generation” dsp.AudioFileWriter “System Objects in MATLAB Code Generation” dsp.UDPSender “System Objects in MATLAB Code Generation” Sources dsp.AudioFileReader “System Objects in MATLAB Code Generation” dsp.AudioRecorder “System Objects in MATLAB Code Generation” dsp.SignalSource “System Objects in MATLAB Code Generation” dsp.SineWave • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.UDPReceiver “System Objects in MATLAB Code Generation” Statistics dsp.Autocorrelator “System Objects in MATLAB Code Generation” dsp.Crosscorrelator “System Objects in MATLAB Code Generation” 4-165 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations dsp.Histogram • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.Maximum “System Objects in MATLAB Code Generation” dsp.Mean “System Objects in MATLAB Code Generation” dsp.Median “System Objects in MATLAB Code Generation” dsp.Minimum “System Objects in MATLAB Code Generation” dsp.PeakToPeak “System Objects in MATLAB Code Generation” dsp.PeakToRMS “System Objects in MATLAB Code Generation” dsp.RMS “System Objects in MATLAB Code Generation” dsp.StandardDeviation “System Objects in MATLAB Code Generation” dsp.StateLevels “System Objects in MATLAB Code Generation” dsp.Variance “System Objects in MATLAB Code Generation” Transforms dsp.AnalyticSignal “System Objects in MATLAB Code Generation” dsp.DCT “System Objects in MATLAB Code Generation” dsp.FFT “System Objects in MATLAB Code Generation” dsp.IDCT “System Objects in MATLAB Code Generation” dsp.IFFT “System Objects in MATLAB Code Generation” Error Handling in MATLAB Function Remarks and Limitations assert • 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. • For standalone code generation, excluded from the generated code. • See “Rules for Using assert Function”. error For standalone code generation, excluded from the generated code. 4-166 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Exponents in MATLAB Function Remarks and Limitations exp — expm — expm1 — factorial — log • 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). log2 — log10 — log1p — nextpow2 — nthroot — reallog — realpow — realsqrt — sqrt • 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). Filtering and Convolution in MATLAB Function Remarks and Limitations conv — conv2 — convn — deconv — 4-167 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations detrend • 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]. 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. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” filter — filter2 — Fixed-Point Designer In addition to function-specific limitations listed in the table, the following general limitations apply to the use of Fixed-Point Designer functions in generated code, with fiaccel: • fipref and quantizer objects are not supported. • Word lengths greater than 128 bits are not supported. • You cannot change the fimath or numerictype of a given fi variable after that variable has been created. • The boolean value 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. • You can use parallel for (parfor) loops in code compiled with fiaccel, but those loops are treated like regular for loops. • 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. 4-168 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List • The general limitations of C/C++ code generated from MATLAB apply. For more information, see “MATLAB Language Features Supported for C/C++ Code Generation”. Function Remarks/Limitations abs N/A accumneg N/A accumpos N/A add • Code generation in MATLAB does not support the syntax F.add(a,b). You must use the syntax add(F,a,b). all N/A any N/A atan2 N/A bitand Not supported for slope-bias scaled fi objects. bitandreduce N/A bitcmp N/A bitconcat N/A bitget N/A bitor Not supported for slope-bias scaled fi objects. bitorreduce N/A bitreplicate N/A bitrol N/A bitror N/A bitset N/A bitshift N/A bitsliceget N/A bitsll Generated code may not handle out of range shifting. bitsra Generated code may not handle out of range shifting. bitsrl Generated code may not handle out of range shifting. bitxor Not supported for slope-bias scaled fi objects. 4-169 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations bitxorreduce N/A ceil N/A complex N/A conj N/A conv • 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 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 N/A cordicabs Variable-size signals are not supported. cordicangle Variable-size signals are not supported. cordicatan2 Variable-size signals are not supported. cordiccart2pol Variable-size signals are not supported. cordiccexp Variable-size signals are not supported. cordiccos Variable-size signals are not supported. cordicpol2cart Variable-size signals are not supported. cordicrotate Variable-size signals are not supported. cordicsin Variable-size signals are not supported. cordicsincos Variable-size signals are not supported. cos N/A ctranspose N/A 4-170 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations diag If supplied, the index, k, must be a real and scalar integer value that is not a fi object. divide • 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 For the automated workflow, do not use explicit double or single casts in your MATLAB algorithm to insulate functions that do not support fixed-point data types. The automated conversion tool does not support these casts. Instead of using casts, supply a replacement function. For more information, see “Function Replacements”. end N/A eps • Supported for scalar fixed-point signals only. • Supported for scalar, vector, and matrix, fi single and fi double signals. eq Not supported for fixed-point signals with different biases. fi • The default constructor syntax without any input arguments is not supported. • If the numerictype is not fully specified, the input to fi must be a constant, a fi, a single, or a built-in integer value. If the input is a built-in double value, it must be a constant. This limitation allows fi to autoscale its fraction length based on the known data type of the input. • All properties related to data type must be constant for code generation. • numerictype object information must be available for nonfixedpoint 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. 4-171 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations fimath • 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. • If the ProductMode property of the fimath object is set to anything other than FullPrecision, the ProductWordLength and ProductFractionLength properties must be constant. • If the SumMode property of the fimath object is set to anything other than FullPrecision, the SumWordLength and SumFractionLength properties must be constant. fix N/A fixed.Quantizer N/A flip The dimensions argument must be a built-in type; it cannot be a fi object. fliplr N/A flipud N/A floor N/A for N/A ge Not supported for fixed-point signals with different biases. get The syntax structure = get(o) is not supported. getlsb N/A getmsb N/A gt Not supported for fixed-point signals with different biases. horzcat N/A imag N/A int8, int16, int32, int64 N/A ipermute N/A iscolumn N/A isempty N/A 4-172 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations isequal N/A isfi Avoid using the isfi function in code that you intend to convert using the automated workflow. The value returned by isfi in the fixed-point code might differ from the value returned in the original MATLAB algorithm. The behavior of the fixed-point code might differ from the behavior of the original algorithm. isfimath N/A isfimathlocal N/A isfinite N/A isinf N/A isnan N/A isnumeric N/A isnumerictype N/A isreal N/A isrow N/A isscalar N/A issigned N/A isvector N/A le Not supported for fixed-point signals with different biases. length N/A logical N/A lowerbound N/A lsb • Supported for scalar fixed-point signals only. • Supported for scalar, vector, and matrix, fi single and double signals. lt Not supported for fixed-point signals with different biases. max N/A mean N/A median N/A 4-173 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations min N/A minus 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. mpower • When the exponent k is a variable and the input is a scalar, the ProductMode property of the governing fimath must be SpecifyPrecision. • When the exponent k is a variable and the input is not scalar, the SumMode property of the governing fimath must be SpecifyPrecision. • Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to SpecifyPrecision 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 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 • Code generation in MATLAB does not support the syntax F.mpy(a,b). You must use the syntax mpy(F,a,b). • 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. mrdivide N/A 4-174 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations mtimes • 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 SpecifyPrecision or KeepLSB. • 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 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 N/A ne Not supported for fixed-point signals with different biases. nearest N/A numberofelements numberofelements will be removed in a future release. Use numel instead. numel N/A numerictype • 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. • All numerictype object properties related to the data type must be constant. permute The dimensions argument must be a built-in type; it cannot be a fi object. plus Any non-fi inputs must be constant; that is, its value must be known at compile time so that it can be cast to a fi object. pow2 N/A 4-175 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations power When the exponent k is a variable, the ProductMode property of the governing fimath must be SpecifyPrecision. qr N/A quantize N/A range N/A rdivide N/A real N/A realmax N/A realmin N/A reinterpretcast N/A removefimath N/A repmat The dimensions argument must be a built-in type; it cannot be a fi object. rescale N/A reshape N/A rot90 In the syntax rot90(A,k), the argument k must be a built-in type; it cannot be a fi object. round N/A setfimath N/A sfi • All properties related to data type must be constant for code generation. shiftdim The dimensions argument must be a built-in type; it cannot be a fi object. sign N/A sin N/A single For the automated workflow, do not use explicit double or single casts in your MATLAB algorithm to insulate functions that do not support fixed-point data types. The automated conversion tool does not support these casts. Instead of using casts, supply a replacement function. For more information, see “Function Replacements”. 4-176 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations size N/A sort The dimensions argument must be a built-in type; it cannot be a fi object. squeeze N/A sqrt • Complex and [Slope Bias] inputs error out. • Negative inputs yield a 0 result. storedInteger N/A storedIntegerToDouble N/A sub • Code generation in MATLAB does not support the syntax F.sub(a,b). You must use the syntax sub(F,a,b). subsasgn N/A subsref N/A sum Variable-sized inputs are only supported when the SumMode property of the governing fimath is set to Specify precision or Keep LSB. times • 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 N/A tril If supplied, the index, k, must be a real and scalar integer value that is not a fi object. triu If supplied, the index, k, must be a real and scalar integer value that is not a fi object. ufi • All properties related to data type must be constant for code generation. uint8, uint16, uint32, uint64 N/A uminus N/A 4-177 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations uplus N/A upperbound N/A vertcat N/A HDL Coder Function Remarks and Limitations hdl.RAM This System object is available with MATLAB. Histograms in MATLAB Function Remarks and Limitations hist • 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. • The output of a variable-size array that becomes a column vector at run time is a column-vector, not a row-vector. histc • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” Image Acquisition Toolbox If you install Image Acquisition Toolbox software, you can generate C and C++ code for the VideoDevice System object. See imaq.VideoDevice and “Code Generation with VideoDevice System Object”. Image Processing in MATLAB Function Remarks and Limitations im2double — 4-178 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Image Processing Toolbox The following table lists the Image Processing Toolbox functions that have been enabled for code generation. You must have the MATLAB Coder and Image Processing Toolbox software installed to generate C code from MATLAB for these functions. Image Processing Toolbox provides three types of code generation support: • Functions that generate C code. • Functions that generate C code that depends on a platform-specific shared library (.dll, .so, or .dylib). Use of a shared library preserves performance optimizations in these functions, but this limits the target platforms for which you can generate code. For more information, see “Code Generation for Image Processing”. • Functions that generate C code or C code that depends on a shared library, depending on which target platform you specify in MATLAB Coder. If you specify the generic MATLAB Host Computer target platform, these functions generate C code that depends on a shared library. If you specify any other target platform, these functions generate C code. In generated code, each supported toolbox function has the same name, arguments, and functionality as its Image Processing Toolbox counterpart. However, some functions have limitations. The following table includes information about code generation limitations that might exist for each function. In the following table, all the functions generate C code. The table identifies those functions that generate C code that depends on a shared library, and those functions that can do both, depending on which target platform you choose. Function Remarks/Limitations affine2d When generating code, you can only specify single objects—arrays of objects are not supported. bwdist The method argument must be a compile-time constant. Input images must have fewer than 232 pixels. Generated code for this function uses a precompiled, “platform-specific shared library”. bwlookup For best results, specify an input image of class logical. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. 4-179 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations bwmorph The text string specifying the operation must be a constant and, for best results, specify an input image of class logical. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. bwpack Generated code for this function uses a precompiled “platform-specific shared library”. bwselect Supports only the 3 and 4 input argument syntaxes: BW2 = bwselect(BW,c,r) and BW2 = bwselect(BW,c,r,n). The optional fourth input argument, n, must be a compile-time constant. In addition, with code generation, bwselect only supports only the 1 and 2 output argument syntaxes: BW2 = bwselect(___) or [BW2, idx] = bwselect(___). Generated code for this function uses a precompiled “platform-specific shared library”. bwtraceboundary The dir, fstep, and conn arguments must be compile-time constants. bwunpack Generated code for this function uses a precompiled “platform-specific shared library”. conndef Input arguments must be compile-time constants. edge The method, direction, and sigma arguments must be a compiletime constants. In addition, nonprogrammatic syntaxes are not supported. For example, the syntax edge(im), where edge does not return a value but displays an image instead, is not supported. Generated code for this function uses a precompiled “platform-specific shared library”. fitgeotrans The transformtype argument must be a compile-time constant. The function supports the following transformation types: 'nonreflectivesimilarity', 'similarity', 'affine', or 'projective'. fspecial Inputs must be compile-time constants. Expressions or variables are allowed if their values do not change. getrangefromclass — 4-180 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations histeq All the syntaxes that include indexed images are not supported. This includes all syntaxes that accept map as input and return newmap. Generated code for this function uses a precompiled “platform-specific shared library”. im2uint8 Generated code for this function uses a precompiled “platform-specific shared library”. im2uint16 Generated code for this function uses a precompiled “platform-specific shared library”. im2int16 Generated code for this function uses a precompiled “platform-specific shared library”. im2single — im2double — imadjust Does not support syntaxes that include indexed images. This includes all syntaxes that accept map as input and return newmap. Generated code for this function uses a precompiled “platform-specific shared library”. imbothat The input image IM must be either 2-D or 3-D image. The structuring element input argument SE must be a compile-time constant. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. imclearborder The optional second input argument, conn, must be a compile-time constant. Supports only up to 3-D inputs. Generated code for this function uses a precompiled “platform-specific shared library”. imclose The input image IM must be either 2-D or 3-D image. The structuring element input argument SE must be a compile-time constant. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. imcomplement Does not support int64 and uint64 data types. 4-181 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations imdilate The input image IM must be either 2-D or 3-D image. The SE, PACKOPT, and SHAPE input arguments must be a compile-time constant. The structuring element argument SE must be a single element—arrays of structuring elements are not supported. To obtain the same result as that obtained using an array of structuring elements, call the function sequentially. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. imerode The input image IM must be either 2-D or 3-D image. The SE, PACKOPT, and SHAPE input arguments must be a compile-time constant. The structuring element argument SE must be a single element—arrays of structuring elements are not supported. To obtain the same result as that obtained using an array of structuring elements, call the function sequentially. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. imextendedmax The optional third input argument, conn, must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. imextendedmin The optional third input argument, conn, must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. 4-182 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations imfill The optional input connectivity, conn and the string 'holes' must be compile-time constants. Supports only up to 3-D inputs. The interactive mode to select points, imfill(BW,0,CONN) is not supported in code generation. locations can be a P-by-1 vector, in which case it contains the linear indices of the starting locations. locations can also be a Pby-ndims(I) matrix, in which case each row contains the array indices of one of the starting locations. Once you select a format at compiletime, you cannot change it at run time. However, the number of points in locations can be varied at run time. Generated code for this function uses a precompiled “platform-specific shared library”. imfilter The input image can be either 2-D or 3-D. The value of the input argument, options, must be a compile-time constant. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. imhist The optional second input argument, n, must be a compile-time constant. In addition, nonprogrammatic syntaxes are not supported. For example, the syntaxes where imhist displays the histogram are not supported. Generated code for this function uses a precompiled “platform-specific shared library”. imhmax The optional third input argument, conn, must be a compile-time constant Generated code for this function uses a precompiled “platform-specific shared library”. 4-183 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations imhmin The optional third input argument, conn, must be a compile-time constant Generated code for this function uses a precompiled “platform-specific shared library”. imlincomb The output_class argument must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. imopen The input image IM must be either 2-D or 3-D image. The structuring element input argument SE must be a compile-time constant. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. imquantize — imreconstruct The optional third input argument, conn, must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. imref2d The XWorldLimits, YWorldLimits and ImageSize properties can be set only during object construction. When generating code, you can only specify single objects—arrays of objects are not supported. imref3d The XWorldLimits, YWorldLimits, ZWorldLimits and ImageSize properties can be set only during object construction. When generating code, you can only specify single objects—arrays of objects are not supported. imregionalmax The optional second input argument, conn, must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. 4-184 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations imregionalmin The optional second input argument, conn, must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. imtophat The input image IM must be either 2-D or 3-D image. The structuring element input argument SE must be a compile-time constant. If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, “platform-specific shared library”. imwarp The geometric transformation object input, tform, must be either affine2d or projective2d. Additionally, the interpolation method and optional parameter names must be string constants. Generated code for this function uses a precompiled “platform-specific shared library”. intlut Generated code for this function uses a precompiled “platform-specific shared library”. iptcheckconn Input arguments must be compile-time constants. iptcheckmap — label2rgb 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'. mean2 — 4-185 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations medfilt2 The padopt argument must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. multithresh — ordfilt2 The padopt argument must be a compile-time constant. Generated code for this function uses a precompiled “platform-specific shared library”. padarray Support only up to 3-D inputs. Input arguments, padval and direction are expected to be compiletime constants. projective2d When generating code, you can only specify single objects—arrays of objects are not supported. rgb2ycbcr — strel Input arguments must be compile-time constants. The following methods are not supported for code generation: getsequence, reflect, translate, disp, display, loadobj. When generating code, you can only specify single objects—arrays of objects are not supported. stretchlim Generated code for this function uses a precompiled “platform-specific shared library”. ycbcr2rgb — Input and Output Arguments in MATLAB Function Remarks and Limitations nargin — nargout • For a function with no output arguments, returns 1 if called without a terminating semicolon. 4-186 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations Note: This behavior also affects extrinsic calls with no terminating semicolon. nargout is 1 for the called function in MATLAB. Interpolation and Computational Geometry in MATLAB Function Remarks and Limitations cart2pol — cart2sph — interp1 “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” interp2 • Xq and Yq must be the same size. Use meshgrid to evaluate on a grid. • For best results, provide X and Y as vectors. • For the 'cubic' method, reports an error if the grid does not have uniform spacing. In this case, use the 'spline' method. • For best results when you use the 'spline' method: • Use meshgrid to create the inputs Xq and Yq. • Use a small number of interpolation points relative to the dimensions of V. Interpolating over a large set of scattered points can be inefficient. interp3 • Xq, Yq, and Zq must be the same size. Use meshgrid to evaluate on a grid. • For best results, provide X, Y, and Z as vectors. • For the 'cubic' method, reports an error if the grid does not have uniform spacing. In this case, use the 'spline' method. • For best results when you use the 'spline' method: • Use meshgrid to create the inputs Xq, Yq, and Zq. • Use a small number of interpolation points relative to the dimensions of V. Interpolating over a large set of scattered points can be inefficient. meshgrid — 4-187 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations mkpp • The output structure pp differs from the pp structure in MATLAB. In MATLAB, ppval cannot use the pp structure from the code generation software. For code generation, ppval cannot use a pp structure created by MATLAB. unmkpp can use a MATLAB pp structure for code generation. To create a MATLAB pp structure from a pp structure created by the code generation software: • In code generation, use unmkpp to return the piecewise polynomial details to MATLAB. • In MATLAB, use mkpp to create the pp structure. • If you do not provide d, then coefs must be two-dimensional and have a fixed number of columns. In this case, the number of columns is the order. • To define a piecewise constant polynomial, coefs must be a column vector or d must have at least two elements. • If you provide d and d is 1, d must be a constant. Otherwise, if the input to ppval is nonscalar, the shape of the output of ppval can differ from ppval in MATLAB. • If you provide d, it must have a fixed length. One of the following sets of statements must be true: 1 Suppose that m = length(d) and npieces = length(breaks) - 1. size(coefs,j) = d(j) size(coefs,m+1) = npieces size(coefs,m+2) = order j = 1,2,...,m. The dimension m+2 must be fixed length. 2 Suppose that m = length(d) and npieces = length(breaks) - 1. size(coefs,1) = prod(d)*npieces size(coefs,2) = order The second dimension must be fixed length. • If you do not provide d, the following statements must be true: 4-188 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations Suppose that m = length(d) and npieces = length(breaks) - 1. size(coefs,1) = prod(d)*npieces size(coefs,2) = order The second dimension must be fixed length. pchip • Input x must be strictly increasing. • Does not remove y entries with NaN values. • If you generate code for the pp = pchip(x,y) syntax, you cannot input pp to the ppval function in MATLAB. To create a MATLAB pp structure from a pp structure created by the code generation software: • In code generation, use unmkpp to return the piecewise polynomial details to MATLAB. • In MATLAB, use mkpp to create the pp structure. pol2cart — polyarea — ppval The size of output v does not match MATLAB when both of the following statements are true: • The input x is a variable-size array that is not a variable-length vector. • x becomes a row vector at run time. The code generation software does not remove the singleton dimensions. However, MATLAB might remove singleton dimensions. For example, suppose that x is a :4-by-:5 array (the first dimension is variable size with an upper bound of 4 and the second dimension is variable size with an upper bound of 5). Suppose that ppval(pp,0) returns a 2by-3 fixed-size array. v has size 2-by-3-by-:4-by-:5. At run time, suppose that, size(x,1) =1 and size (x,2) = 5. In the generated code, the size(v) is [2,3,1,5]. In MATLAB, the size is [2,3,5]. rectint — sph2cart — 4-189 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations spline • Input x must be strictly increasing. • Does not remove Y entries with NaN values. • Does not report an error for infinite endslopes in Y. • If you generate code for the pp = spline(x,Y) syntax, you cannot input pp to the ppval function in MATLAB. To create a MATLAB pp structure from a pp structure created by the code generation software: • In code generation, use unmkpp to return the piecewise polynomial details to MATLAB. • In MATLAB, use mkpp to create the pp structure. • pp must be a valid piecewise polynomial structure created by mkpp, spline, or pchip in MATLAB or by the code generation software. unmkpp • Does not support pp structures created by interp1 in MATLAB. Linear Algebra in MATLAB Function Remarks and Limitations ishermitian — issymmetric — linsolve • 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 Other options are equivalent to using mldivide. null • Might return a different basis than MATLAB • Does not support rational basis option (second input) 4-190 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations orth • Can return a different basis than MATLAB rsf2csf — schur Can return a different Schur decomposition in generated code than in MATLAB. sqrtm — Logical and Bit-Wise Operations in MATLAB Function Remarks and Limitations and — bitand — bitcmp — bitget — bitor — bitset — bitshift — bitxor — not — or — xor — MATLAB Compiler C and C++ code generation for the following functions requires the MATLAB Compiler software. Function Remarks and Limitations isdeployed • Returns true and false as appropriate for MEX and SIM targets • Returns false for other targets 4-191 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations ismcc • Returns true and false as appropriate for MEX and SIM targets. • Returns false for other targets. Matrices and Arrays in MATLAB Function Remarks and Limitations abs — all “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” angle — any “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” blkdiag — bsxfun “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” cat • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” circshift — colon • Does not accept complex inputs. • The input i cannot have a logical value. • Does not accept vector inputs. • Inputs must be constants. • Uses single-precision arithmetic to produce single-precision results. compan — cond “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” cov “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” cross • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” cumprod • Does not support logical inputs. Cast input to double first. • Does not support the direction argument. 4-192 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations cumsum • Does not support logical inputs. Cast input to double first. • Does not support the direction argument. det — diag • If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. • For variable-size inputs that are variable-length vectors (1-by-: or :by-1), diag: • Treats the input as a vector input. • Returns a matrix with the given vector along the specified diagonal. • For variable-size inputs that are not variable-length vectors, diag: • Treats the input as a matrix. • Does not support inputs that are vectors at run time. • Returns a variable-length vector. If the input is variable-size (:m-by-:n) and has shape 0-by-0 at run time, the output is 0-by-1 not 0-by-0. However, if the input is a constant size 0-by-0, the output is []. • For variable-size inputs that are not variable-length vectors (1-by-: or :-by-1), diag treats the input as a matrix from which to extract a diagonal vector. This behavior occurs even if the input array is a vector at run time. To force diag to build a matrix from variablesize inputs that are not 1-by-: or :-by-1, use: • diag(x(:)) instead of diag(x) • diag(x(:),k) instead of diag(x,k) • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-193 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations diff • If supplied, the arguments representing the number of times to apply diff and the dimension along which to calculate the difference must be constants. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” dot — eig • For code generation,QZ algorithm is used in all cases. MATLAB can use different algorithms for different inputs. Consequently, V might represent a different basis of eigenvectors. The eigenvalues in D might not be in the same order as in MATLAB. • With one input, [V,D] = eig(A), the results are 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', and 'nobalance' are not supported for the standard eigenvalue problem. 'chol' is not supported for the symmetric generalized eigenvalue problem. • Outputs are of complex type. • Does not support the option to calculate left eigenvectors. eye classname must be a built-in MATLAB numeric type. Does not invoke the static eye method for other classes. For example, eye(m, n, 'myclass’) does not invoke myclass.eye(m,n). false • Dimensions must be real, nonnegative, integers. find • 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, 0by-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. 4-194 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations flip — flipdim Note: flipdim will be removed in a future release. Use flip instead. fliplr — flipud — full — hadamard — hankel — hilb — ind2sub • The first argument should be a valid size vector. Size vectors for arrays with more than intmax elements are not supported. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” inv Singular matrix inputs can produce nonfinite values that differ from MATLAB results. invhilb — ipermute “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” iscolumn — isempty — isequal — isequaln — isfinite — isfloat — isinf — isinteger — islogical — ismatrix — isnan — isrow — 4-195 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations issparse — isvector — kron — length — linspace — logspace — lu — magic “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” max • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” min • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” ndgrid — ndims — nnz — nonzeros — norm — normest — numel — ones • Dimensions must be real, nonnegative integers. • The input optimfun must be a function supported for code generation. pascal — permute “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” pinv — planerot “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-196 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations prod • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” qr — rand • classname must be a built-in MATLAB numeric type. Does not invoke the static rand method for other classes. For example, rand(sz,'myclass’) does not invoke myclass.rand(sz). • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” randi • classname must be a built-in MATLAB numeric type. Does not invoke the static randi method for other classes. For example, randi(imax,sz,'myclass’) does not invoke myclass.randi(imax,sz). • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” randn • classname must be a built-in MATLAB numeric type. Does not invoke the static randn method for other classes. For example, randn(sz,'myclass’) does not invoke myclass.randn(sz). • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” randperm — rank — rcond — repmat — reshape • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-197 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations rng • For library code generation targets, executable code generation targets, and MEX targets with extrinsic calls disabled: • Does not support the 'shuffle' input. • For the generator input, supports 'twister', 'v4', and 'v5normal'. For these targets, the output of s=rng in the generated code differs from the MATLAB output. You cannot return the output of s=rng from the generated code and pass it to rng in MATLAB. • For MEX targets, if extrinsic calls are enabled, you cannot access the data in the structure returned by rng. rosser — rot90 — shiftdim • Second argument must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” sign — size — sort If the input is a complex type, sort orders the output according to absolute value. When x is a complex type that has all zero imaginary parts, use sort(real(x)) to compute the sort order for real types. See “Code Generation for Complex Data”. sortrows If the input is a complex type, sortrows orders the output according to absolute value. When x is a complex type that has all zero imaginary parts, use sortrows(real(x)) to compute the sort order for real types. See “Code Generation for Complex Data”. squeeze — sub2ind • The first argument should be a valid size vector. Size vectors for arrays with more than intmax elements are not supported. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” subspace — 4-198 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations sum • Specify dim as a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” toeplitz — trace — tril • If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. triu • If supplied, the argument representing the order of the diagonal matrix must be a real and scalar integer value. true • Dimensions must be real, nonnegative, integers. vander — wilkinson — zeros • Dimensions must be real, nonnegative, integers. Neural Network Toolbox You can use genFunction in the Neural Network Toolbox™ to generate a standalone MATLAB function for a trained neural network. You can generate C/C++ code from this standalone MATLAB function. To generate Simulink blocks, use thegenSim function. See “Deploy Neural Network Functions”. Nonlinear Numerical Methods in MATLAB Function Remarks and Limitations quad2d • Generates a warning if the size of the internal storage arrays is not large enough. If a warning occurs, a possible workaround is to divide the region of integration into pieces and sum the integrals over each piece. quadgk — Numerical Integration and Differentiation in MATLAB Function Remarks and Limitations cumtrapz — 4-199 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations del2 — diff • If supplied, the arguments representing the number of times to apply diff and the dimension along which to calculate the difference must be constants. gradient — ode23 • All odeset option arguments must be constant. • Does not support a constant mass matrix in the options structure. Provide a mass matrix as a function . • You must provide at least the two output arguments T and Y. • Input types must be homogeneous—all double or all single. • Variable-sizing support must be enabled. Requires dynamic memory allocation when tspan has two elements or you use event functions. • All odeset option arguments must be constant. ode45 • Does not support a constant mass matrix in the options structure. Provide a mass matrix as a function . • You must provide at least the two output arguments T and Y. • Input types must be homogeneous—all double or all single. • Variable-sizing support must be enabled. Requires dynamic memory allocation when tspan has two elements or you use event functions. odeget The name argument must be constant. odeset All inputs must be constant. trapz • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” Optimization Functions in MATLAB Function Remarks and Limitations fminsearch • Ignores the Display option. Does not print status information during execution. Test the exitflag output for the exit condition. • The output structure does not include the algorithm or message fields. 4-200 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations • Ignores the OutputFcn and PlotFcns options. fzero • 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). optimget Input parameter names must be constant. optimset • Does not support the syntax that has no input or output arguments: optimset • Functions specified in the options must be supported for code generation. • The fields of the options structure oldopts must be fixed-size fields. • For code generation, optimization functions ignore the Display option. • Does not support the additional options in an options structure created by the Optimization Toolbox optimset function. If an input options structure includes the additional Optimization Toolbox options, the output structure does not include them. Phased Array System Toolbox C and C++ code generation for the following functions requires the Phased Array System Toolbox software. Name Remarks and Limitations Antenna and Microphone Elements aperture2gain Does not support variable-size inputs. azel2phithetapat Does not support variable-size inputs. azel2uvpat Does not support variable-size inputs. circpol2pol Does not support variable-size inputs. gain2aperture Does not support variable-size inputs. phased.CosineAntennaElement • plotResponse and viewArray methods are not supported. • “Code Generation”. 4-201 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations phased.CrossedDipoleAntennaElement • plotResponse and viewArray methods are not supported. • “Code Generation”. • plotResponse and viewArray methods are not supported. phased.CustomAntennaElement • “Code Generation”. phased.CustomMicrophoneElement • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.IsotropicAntennaElement • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.OmnidirectionalMicrophoneElement• plotResponse and viewArray methods are not supported. • “Code Generation”. phased.ShortDipoleAntennaElement • plotResponse and viewArray methods are not supported. • “Code Generation”. phitheta2azelpat Does not support variable-size inputs. phitheta2uvpat Does not support variable-size inputs. pol2circpol Does not support variable-size inputs. polellip Does not support variable-size inputs. polloss Does not support variable-size inputs. polratio Does not support variable-size inputs. polsignature • Does not support variable-size inputs. • Supported only when output arguments are specified. stokes • Does not support variable-size inputs. • Supported only when output arguments are specified. 4-202 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations uv2azelpat Does not support variable-size inputs. uv2phithetapat Does not support variable-size inputs. Array Geometries and Analysis az2broadside Does not support variable-size inputs. broadside2az Does not support variable-size inputs. phased.ArrayGain • Does not support arrays containing polarized antenna elements, that is, the phased.ShortDipoleAntennaElement or phased.CrossedDipoleAntennaElement antennas. • “Code Generation”. phased.ArrayResponse “Code Generation”. phased.ConformalArray • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.ElementDelay “Code Generation”. phased.PartitionedArray • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.ReplicatedSubarray • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.SteeringVector See “Code Generation”. phased.ULA • plotResponse and viewArray methods are not supported. • “Code Generation”. phased.URA • plotResponse and viewArray methods are not supported. • “Code Generation”. Signal Radiation and Collection 4-203 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations phased.Collector “Code Generation”. phased.Radiator “Code Generation”. phased.WidebandCollector • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. sensorsig Does not support variable-size inputs. Waveforms ambgfun Does not support variable-size inputs. phased.FMCWWaveform “Code Generation”. phased.LinearFMWaveform “Code Generation”. phased.PhaseCodedWaveform “Code Generation”. phased.RectangularWaveform “Code Generation”. phased.SteppedFMWaveform “Code Generation”. range2bw Does not support variable-size inputs. range2time Does not support variable-size inputs. time2range Does not support variable-size inputs. unigrid Does not support variable-size inputs. Transmitters and Receivers delayseq Does not support variable-size inputs. noisepow Does not support variable-size inputs. phased.ReceiverPreamp “Code Generation”. phased.Transmitter “Code Generation”. systemp Does not support variable-size inputs. Beamforming cbfweights Does not support variable-size inputs. lcmvweights Does not support variable-size inputs. mvdrweights Does not support variable-size inputs. 4-204 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations phased.FrostBeamformer • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. phased.LCMVBeamformer “Code Generation”. phased.MVDRBeamformer “Code Generation”. phased.PhaseShiftBeamformer “Code Generation”. phased.SteeringVector “Code Generation”. phased.SubbandPhaseShiftBeamformer “Code Generation”. phased.TimeDelayBeamformer • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. phased.TimeDelayLCMVBeamformer • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. sensorcov Does not support variable-size inputs. steervec Does not support variable-size inputs. Direction of Arrival (DOA) Estimation aictest Does not support variable-size inputs. espritdoa Does not support variable-size inputs. mdltest Does not support variable-size inputs. phased.BeamscanEstimator “Code Generation”. phased.BeamscanEstimator2D “Code Generation”. phased.BeamspaceESPRITEstimator “Code Generation”. phased.ESPRITEstimator “Code Generation”. phased.MVDREstimator “Code Generation”. phased.MVDREstimator2D “Code Generation”. 4-205 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations phased.RootMUSICEstimator “Code Generation”. phased.RootWSFEstimator “Code Generation”. phased.SumDifferenceMonopulseTracker “Code Generation”. phased.SumDifferenceMonopulseTracker2D “Code Generation”. rootmusicdoa Does not support variable-size inputs. spsmooth Does not support variable-size inputs. Space-Time Adaptive Processing (STAP) dopsteeringvec Does not support variable-size inputs. phased.ADPCACanceller “Code Generation”. phased.AngleDopplerResponse “Code Generation”. phased.DPCACanceller “Code Generation”. phased.STAPSMIBeamformer “Code Generation”. val2ind Does not support variable-size inputs. Signal Propagation and Environment billingsleyicm Does not support variable-size inputs. depressionang Does not support variable-size inputs. effearthradius Does not support variable-size inputs. fspl Does not support variable-size inputs. grazingang Does not support variable-size inputs. horizonrange Does not support variable-size inputs. phased.BarrageJammer “Code Generation”. phased.ConstantGammaClutter “Code Generation”. phased.FreeSpace • Requires dynamic memory allocation. See “Limitations for System Objects that Require Dynamic Memory Allocation”. • “Code Generation”. phased.RadarTarget “Code Generation”. physconst Does not support variable-size inputs. 4-206 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Name Remarks and Limitations surfacegamma Does not support variable-size inputs. surfclutterrcs Does not support variable-size inputs. Detection and System Analysis albersheim Does not support variable-size inputs. beat2range Does not support variable-size inputs. dechirp Does not support variable-size inputs. npwgnthresh Does not support variable-size inputs. phased.CFARDetector “Code Generation”. phased.MatchedFilter • The CustomSpectrumWindow property is not supported. • “Code Generation”. phased.RangeDopplerResponse • The CustomRangeWindow and the CustomDopplerWindow properties are not supported. • “Code Generation”. phased.StretchProcessor “Code Generation”. phased.TimeVaryingGain “Code Generation”. pulsint Does not support variable-size inputs. radareqpow Does not support variable-size inputs. radareqrng Does not support variable-size inputs. radareqsnr Does not support variable-size inputs. radarvcd Does not support variable-size inputs. range2beat Does not support variable-size inputs. rdcoupling Does not support variable-size inputs. rocpfa • Does not support variable-size inputs. • The NonfluctuatingNoncoherent signal type is not supported. 4-207 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Name Remarks and Limitations rocsnr • Does not support variable-size inputs. • The NonfluctuatingNoncoherent signal type is not supported. shnidman Does not support variable-size inputs. stretchfreq2rng Does not support variable-size inputs. Motion Modeling and Coordinate Systems azel2phitheta Does not support variable-size inputs. azel2uv Does not support variable-size inputs. azelaxes Does not support variable-size inputs. cart2sphvec Does not support variable-size inputs. dop2speed Does not support variable-size inputs. global2localcoord Does not support variable-size inputs. local2globalcoord Does not support variable-size inputs. phased.Platform “Code Generation”. phitheta2azel Does not support variable-size inputs. phitheta2uv Does not support variable-size inputs. radialspeed Does not support variable-size inputs. rangeangle Does not support variable-size inputs. rotx Does not support variable-size inputs. roty Does not support variable-size inputs rotz Does not support variable-size inputs. speed2dop Does not support variable-size inputs. sph2cartvec Does not support variable-size inputs. uv2azel Does not support variable-size inputs. uv2phitheta Does not support variable-size inputs. 4-208 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Polynomials in MATLAB Function Remarks and Limitations poly • Does not discard nonfinite input values • Complex input produces complex output • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” polyder The output can contain fewer NaNs than the MATLAB output. However, if the input contains a NaN, the output contains at least one NaN. polyfit “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” polyint — polyval — polyvalm — roots • Output is variable size. • Output is complex. • Roots are not always in the same order as MATLAB. • Roots of poorly conditioned polynomials do not always match MATLAB. Programming Utilities in MATLAB Function Remarks and Limitations mfilename — Relational Operators in MATLAB Function Remarks and Limitations eq — ge — gt — le — lt — ne — 4-209 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Rounding and Remainder Functions in MATLAB Function Remarks and Limitations ceil — fix — floor — mod • Performs the arithmetic using the output class. Results might not match MATLAB due to differences in rounding errors. If one of the inputs has type int64 or uint64, then both inputs must have the same type. • Performs the arithmetic using the output class. Results might not match MATLAB due to differences in rounding errors. rem • If one of the inputs has type int64 or uint64, then both inputs must have the same type. — round Set Operations in MATLAB Function Remarks and Limitations intersect • When you do not specify the 'rows' option: • Inputs A and B must be vectors. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example, zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0-by-0. • When you specify both the 'legacy' option and the 'rows' option, the outputs ia and ib are 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. 4-210 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations • When the setOrder is 'sorted' or when you specify the 'legacy' option, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). ismember • The second input, B, must be sorted in ascending order. • Complex inputs must be single or double. issorted “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” 4-211 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations setdiff • When you do not specify the 'rows' option: • Inputs A and B must be vectors. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • Do not use [] to represent the empty set. Use a 1-by-0 or 0-by-1 input, for example, zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0-by-0. • When you specify both the 'legacy' and 'rows' options, the output ia is a column vector. If ia is empty, it is 0-by-1, never 0-by-0, even if the output C is 0-by-0. • When the setOrder is 'sorted' or when you specify the 'legacy' option, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). 4-212 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations setxor • When you do not specify the 'rows' option: • Inputs A and B must be vectors with the same orientation. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example , zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0-by-0. • When you specify both the 'legacy' option and the 'rows' option, the outputs ia and ib are 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. • When the setOrder is 'sorted' or when you specify the 'legacy' flag, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). 4-213 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations union • When you do not specify the 'rows' option: • Inputs A and B must be vectors with the same orientation. If you specify the 'legacy' option, inputs A and B must be row vectors. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example , zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0-by-0. • When you specify both the 'legacy' option and the 'rows' option, the outputs ia and ib are 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. • When the setOrder is 'sorted' or when you specify the 'legacy' option, the inputs must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. • When one input is complex and the other input is real, do one of the following: • Set setOrder to 'stable'. • Sort the real input in complex ascending order (by absolute value). Suppose the real input is x. Use sort(complex(x))or sortrows(complex(x)). 4-214 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations unique • When you do not specify the'rows' option: • The input A must be a vector. If you specify the 'legacy' option, the input A must be a row vector. • The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1. • The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for example, zeros(1,0), to represent the empty set. • If you specify the 'legacy' option, empty outputs are row vectors, 1-by-0, never 0-by-0. • When you specify both the 'rows' option and the 'legacy'option, outputs ia and ic are column vectors. If these outputs are empty, they are 0-by-1, even if the output C is 0-by-0. • When the setOrder is 'sorted' or when you specify the 'legacy' option, the input A must already be sorted in ascending order. The first output, C, is sorted in ascending order. • Complex inputs must be single or double. Signal Processing in MATLAB Function Remarks and Limitations chol — conv — fft • Length of input vector must be a power of 2. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” fft2 • Length of input matrix dimensions must each be a power of 2. fftn • Length of input matrix dimensions must each be a power of 2. fftshift — filter • If supplied, dim must be a constant. • v freqspace — 4-215 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations ifft • Length of input vector must be a power of 2. • Output of ifft block is complex. • Does not support the 'symmetric' option. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” • Length of input matrix dimensions must each be a power of 2. ifft2 • Does not support the 'symmetric' option. • Length of input matrix dimensions must each be a power of 2. ifftn • Does not support the 'symmetric' option. ifftshift — svd Uses a different SVD implementation than MATLAB. Because the singular value decomposition is not unique, left and right singular vectors might differ from those computed by MATLAB. zp2tf — Signal Processing Toolbox C and C++ code generation for the following functions requires the Signal Processing Toolbox software. These functions do not support variable-size inputs, you must define the size and type of the function inputs. For more information, see “Specifying Inputs in Code Generation from MATLAB ”. Note: Many Signal Processing Toolbox functions require constant inputs in generated code. To specify a constant input for codegen, use coder.Constant. Function Remarks/Limitations barthannwin Window length must be a constant. Expressions or variables are allowed if their values do not change. bartlett Window length must be a constant. Expressions or variables are allowed if their values do not change. besselap Filter order must be a constant. Expressions or variables are allowed if their values do not change. 4-216 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations bitrevorder — blackman Window length must be a constant. Expressions or variables are allowed if their values do not change. blackmanharris Window length must be a constant. Expressions or variables are allowed if their values do not change. bohmanwin Window length must be a constant. Expressions or variables are allowed if their values do not change. buttap Filter order must be a constant. Expressions or variables are allowed if their values do not change. butter Filter coefficients must be constants. Expressions or variables are allowed if their values do not change. buttord All inputs must be constants. Expressions or variables are allowed if their values do not change. cfirpm All inputs must be constants. Expressions or variables are allowed if their values do not change. cheb1ap All inputs must be constants. Expressions or variables are allowed if their values do not change. cheb2ap All inputs must be constants. Expressions or variables are allowed if their values do not change. cheb1ord All inputs must be constants. Expressions or variables are allowed if their values do not change. cheb2ord All inputs must be constants. Expressions or variables are allowed if their values do not change. chebwin All inputs must be constants. Expressions or variables are allowed if their values do not change. cheby1 All Inputs must be constants. Expressions or variables are allowed if their values do not change. cheby2 All inputs must be constants. Expressions or variables are allowed if their values do not change. db2pow — 4-217 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations dct C and C++ code generation for dct requires DSP System Toolbox software. 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. downsample — dpss All inputs must be constants. Expressions or variables are allowed if their values do not change. ellip Inputs must be constant. Expressions or variables are allowed if their values do not change. ellipap All inputs must be constants. Expressions or variables are allowed if their values do not change. ellipord All inputs must be constants. Expressions or variables are allowed if their values do not change. filtfilt Filter coefficients must be constants. Expressions or variables are allowed if their values do not change. findpeaks — fir1 All inputs must be constants. Expressions or variables are allowed if their values do not change. fir2 All inputs must be constants. Expressions or variables are allowed if their values do not change. fircls All inputs must be constants. Expressions or variables are allowed if their values do not change. fircls1 All inputs must be constants. Expressions or variables are allowed if their values do not change. firls All inputs must be constants. Expressions or variables are allowed if their values do not change. firpm All inputs must be constants. Expressions or variables are allowed if their values do not change. firpmord All inputs must be constants. Expressions or variables are allowed if their values do not change. 4-218 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations flattopwin All inputs must be constants. Expressions or variables are allowed if their values do not change. freqz When called with no output arguments, and without a semicolon at the end, freqz returns the complex frequency response of the input filter, evaluated at 512 points. If the semicolon is added, the function produces a plot of the magnitude and phase response of the filter. See “freqz With No Output Arguments”. gausswin All inputs must be constant. Expressions or variables are allowed if their values do not change. hamming All inputs must be constant. Expressions or variables are allowed if their values do not change. hann All inputs must be constant. Expressions or variables are allowed if their values do not change. idct C and C++ code generation for idct requires DSP System Toolbox software. 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. intfilt All inputs must be constant. Expressions or variables are allowed if their values do not change. kaiser All inputs must be constant. Expressions or variables are allowed if their values do not change. kaiserord — levinson C and C++ code generation for levinson requires DSP System Toolbox software. If specified, the order of recursion must be a constant. Expressions or variables are allowed if their values do not change. maxflat All inputs must be constant. Expressions or variables are allowed if their values do not change. 4-219 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks/Limitations nuttallwin All inputs must be constant. Expressions or variables are allowed if their values do not change. parzenwin All inputs must be constant. Expressions or variables are allowed if their values do not change. pow2db — rcosdesign All inputs must be constant. Expressions or variables are allowed if their values do not change. rectwin All inputs must be constant. Expressions or variables are allowed if their values do not change. resample The upsampling and downsampling factors must be specified as constants. Expressions or variables are allowed if their values do not change. sgolay All inputs must be constant. Expressions or variables are allowed if their values do not change. sosfilt — taylorwin All inputs must be constant. Expressions or variables are allowed if their values do not change. triang All inputs must be constant. Expressions or variables are allowed if their values do not change. tukeywin All inputs must be constant. Expressions or variables are allowed if their values do not change. upfirdn C and C++ code generation for upfirdn requires DSP System Toolbox software. 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. upsample 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) xcorr — 4-220 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks/Limitations yulewalk If specified, the order of recursion must be a constant. Expressions or variables are allowed if their values do not change. Special Values in MATLAB Function Remarks and Limitations eps • Supported for scalar fixed-point signals only. • Supported for scalar, vector, and matrix, fi single and fi double signals. inf • Dimensions must be real, nonnegative, integers. intmax — intmin — NaN or nan • Dimensions must be real, nonnegative, integers. pi — realmax — realmin — Specialized Math in MATLAB Function Remarks and Limitations beta — betainc Always returns a complex result. betaincinv Always returns a complex result. betaln — ellipke — erf — erfc — erfcinv — erfcx — 4-221 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations erfinv — expint — gamma — gammainc Output is always complex. gammaincinv Output is always complex. gammaln — psi — Statistics in MATLAB Function Remarks and Limitations corrcoef • Row-vector input is only supported when the first two inputs are vectors and nonscalar. mean • Does not support the 'native' output class option for integer types. • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” median • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”“Variable-Sizing Restrictions for Code Generation of Toolbox Functions” mode • Does not support third output argument C (cell array). • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” std “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” var • If supplied, dim must be a constant. • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” Statistics Toolbox C and C++ code generation for the following functions requires the Statistics Toolbox software. 4-222 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations betacdf — betainv — betapdf — betarnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. betastat — binocdf — binoinv — binopdf — binornd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. binostat — cdf — chi2cdf — chi2inv — chi2pdf — chi2rnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. chi2stat — evcdf — evinv — evpdf — 4-223 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations evrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. evstat — expcdf — expinv — exppdf — exprnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. expstat — fcdf — finv — fpdf — frnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. fstat — gamcdf — gaminv — gampdf — gamrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. 4-224 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations gamstat — geocdf — geoinv — geomean — geopdf — geornd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. geostat — gevcdf — gevinv — gevpdf — gevrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. gevstat — gpcdf — gpinv — gppdf — gprnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. gpstat — harmmean — hygecdf — 4-225 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations hygeinv — hygepdf — hygernd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. hygestat — icdf — iqr — kurtosis — logncdf — logninv — lognpdf — lognrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. lognstat — mad Input dim cannot be empty. mnpdf Input dim cannot be empty. moment If order is nonintegral and X is real, use moment(complex(X), order). nancov If the input is variable-size and is [] at run time, returns [] not NaN. nanmax — nanmean — nanmedian — nanmin — nanstd — 4-226 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations nansum — nanvar — nbincdf — nbininv — nbinpdf — nbinrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. nbinstat — ncfcdf — ncfinv — ncfpdf — ncfrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. ncfstat — nctcdf — nctinv — nctpdf — nctrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. nctstat — ncx2cdf — 4-227 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations ncx2rnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. ncx2stat — normcdf — norminv — normpdf — normrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. normstat — pdf — poisscdf — poissinv — poisspdf — poissrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. poisstat — 4-228 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations prctile • “Automatic dimension restriction” • If the output Y is a vector, the orientation of Y differs from MATLAB when all of the following are true: • You do not supply the dim input. • X is a variable-size array. • X is not a variable-length vector. • X is a vector at run time. • The orientation of the vector X does not match the orientation of the vector p. In this case, the output Y matches the orientation of X not the orientation of p. quantile — randg — random — raylcdf — raylinv — raylpdf — raylrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. raylstat — skewness — tcdf — tinv — tpdf — 4-229 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations trnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. tstat — unidcdf — unidinv — unidpdf — unidrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. unidstat — unifcdf — unifinv — unifpdf — unifrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. unifstat — wblcdf — wblinv — wblpdf — wblrnd Can return a different sequence of numbers than MATLAB if either of the following is true: • The output is nonscalar. • An input parameter is invalid for the distribution. 4-230 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations wblstat — zscore — String Functions in MATLAB Function Remarks and Limitations bin2dec • Does not match MATLAB when the input is empty. bitmax — blanks — char — deblank • Supports only inputs from the char class. • Input values must be in the range 0-127. dec2bin • If input d is double, d must be less than 2^52. • If input d is single, d must be less than 2^23. • Unless you specify input n to be constant and n is large enough that the output has a fixed number of columns regardless of the input values, this function requires variable-sizing support. Without variable-sizing support, n must be at least 52 for double, 23 for single, 16 for char, 32 for int32, 16 for int16, and so on. dec2hex • If input d is double, d must be less than 2^52. • If input d is single, d must be less than 2^23. • Unless you specify input n to be constant and n is large enough that the output has a fixed number of columns regardless of the input values, this function requires variable-sizing support. Without variable-sizing support, n must be at least 13 for double, 6 for single, 4 for char, 8 for int32, 4 for int16, and so on. hex2dec — hex2num • For n = hex2num(S), size(S,2) <= length(num2hex(0)) ischar — isletter • Input values from the char class must be in the range 0-127 isspace • Input values from the char class must be in the range 0–127. 4-231 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations isstrprop • Supports only inputs from char and integer classes. • Input values must be in the range 0-127. lower • Supports only char inputs. • Input values must be in the range 0-127. num2hex — str2double • Does not support cell arrays. • Always returns a complex result. strcmp — strcmpi Input values from the char class must be in the range 0-127. strfind • Does not support cell arrays. • If pattern does not exist in str, returns zeros(1,0) not []. To check for an empty return, use isempty. • Inputs must be character row vectors. strjust — strncmp — strncmpi • Input values from the char class must be in the range 0-127. strrep • Does not support cell arrays. • If oldSubstr does not exist in origStr, returns blanks(0). To check for an empty return, use isempty. • Inputs must be character row vectors. strtok — strtrim • Supports only inputs from the char class. • Input values must be in the range 0-127. upper • Supports only char inputs. • Input values must be in the range 0-127. 4-232 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Structures in MATLAB Function Remarks and Limitations isfield • Does not support cell input for second argument isstruct — struct — Trigonometry in MATLAB Function Remarks and Limitations acos • 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 • 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). acot — acotd — acoth — acsc — acscd — acsch — asec — asecd — asech — asin • 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 — 4-233 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Functions, Classes, and System Objects Supported for Code Generation Function Remarks and Limitations asinh — atan — atan2 — atan2d — atand — atanh 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). cos — cosd — cosh — cot — cotd • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. coth — csc — cscd • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. csch — hypot — sec — secd • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. sech — sin — sind — sinh — tan — 4-234 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and Objects Supported for C and C++ Code Generation — Category List Function Remarks and Limitations tand • In some cases, returns -Inf when MATLAB returns Inf. • In some cases, returns Inf when MATLAB returns -Inf. tanh — 4-235 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-236 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation • “Variables Definition for Code Generation” on page 5-2 • “Best Practices for Defining Variables for C/C++ Code Generation” on page 5-3 • “Eliminate Redundant Copies of Variables in Generated Code” on page 5-7 • “Reassignment of Variable Properties” on page 5-9 • “Define and Initialize Persistent Variables” on page 5-10 • “Reuse the Same Variable with Different Properties” on page 5-11 • “Avoid Overflows in for-Loops” on page 5-15 • “Supported Variable Types” on page 5-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation Variables Definition 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 if(c>0) x = 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 x = zeros(1,3); if(c>0) x = 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 5-3. 5-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 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 5-3 “Use Caution When Reassigning Variables” on page 5-5 “Use Type Cast Operators in Variable Definitions” on page 5-5 “Define Matrices Before Assigning Indexed Variables” on page 5-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: Defines: a = 14.7; a as a real double scalar. b = a; b with properties of a (real double scalar). c = zeros(5,2); c as a real 5-by-2 array of doubles. d = [1 2 3 4 5; 6 7 8 9 0]; d as a real 5-by-2 array of doubles. y = int16(3); y as a real 16-bit integer scalar. Define properties this way so that the variable is defined on the required execution paths during C/C++ code generation (see Defining a Variable for Multiple Execution Paths). 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 Defining Fields in a Structure). 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 “Eliminate Redundant Copies of Variables in Generated Code” on page 5-7. 5-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation When you define variables, they are local by default; they do not persist between function calls. To make variables persistent, see “Define and Initialize Persistent Variables” on page 5-10. 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 ... Defining Fields in a Structure Consider the following MATLAB code: ... if c > 0 s.a = 11; disp(s); else s.a = 12; 5-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Best Practices for Defining Variables for C/C++ Code Generation 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 “Structure Definition for Code Generation”. 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); ... 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 “Reassignment of Variable Properties” on page 5-9. 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: ... 5-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation x = 15; % x is of type double by default. y = uint8(x); % y 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 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 “Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation” on page 7-30. 5-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Eliminate Redundant Copies of Variables in Generated Code Eliminate Redundant Copies of Variables in Generated Code In this section... “When Redundant Copies Occur” on page 5-7 “How to Eliminate Redundant Copies by Defining Uninitialized Variables” on page 5-7 “Defining Uninitialized Variables” on page 5-8 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 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 5-7. 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. 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). 5-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation 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 5-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Reassignment of Variable Properties Reassignment of 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 “Variable-Size Data”. 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 “Reuse the Same Variable with Different Properties” on page 5-11. 5-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation Define and Initialize 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 5-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Reuse the Same Variable with Different Properties Reuse the Same Variable with Different Properties In this section... “When You Can Reuse the Same Variable with Different Properties” on page 5-11 “When You Cannot Reuse Variables” on page 5-11 “Limitations of Variable Reuse” on page 5-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”). 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. 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 5-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation 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 ifelse 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); 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. 5-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Reuse the Same Variable with Different Properties When the compilation is complete, codegen 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. 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. 5-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation The report displays a list of 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. • The block outputs of a MATLAB Function block in a Simulink model. • Chart-owned variables of a MATLAB function in a Stateflow® chart. 5-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Avoid Overflows in for-Loops Avoid Overflows in for-Loops When memory integrity checks are enabled, if the code generation software detects that a loop variable might overflow on the last iteration of the for-loop, it reports an error. To avoid this error, use the workarounds provided in the following table. Loop conditions causing the error Workaround • The loop counter increments by 1 Rewrite the loop so that the end value is not equal to the maximum value of the integer type. For example, replace: • The end value equals the maximum value of the integer type • The loop is not covering the full range of N=intmax('int16') for k=N-10:N the integer type with: for k=1:10 • The loop counter decrements by 1 • The end value equals the minimum value of the integer type Rewrite the loop so that the end value is not equal to the minimum value of the integer type. For example, replace: • The loop is not covering the full range of N=intmin('int32') for k=N+10:-1:N the integer type with: for k=10:-1:1 • The loop counter increments or decrements by 1 • The start value equals the minimum or maximum value of the integer type Rewrite the loop casting the type of the loop counter start, step, and end values to a bigger integer or to double For example, rewrite: • The end value equals the maximum or minimum value of the integer type M= intmin('int16'); N= intmax('int16'); for k=M:N The loop covers the full range of the integer % Loop body end type. to M= intmin('int16'); N= intmax('int16'); for k=int32(M):int32(N) % Loop body 5-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Defining MATLAB Variables for C/C++ Code Generation Loop conditions causing the error Workaround end • The loop counter increments or decrements by a value not equal to 1 • On last loop iteration, the loop variable value is not equal to the end value Rewrite the loop so that the loop variable on the last loop iteration is equal to the end value. Note: The software error checking is conservative. It may incorrectly report a loop as being potentially infinite. 5-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Supported Variable Types Supported Variable Types You can use the following data types for C/C++ code generation from MATLAB: Type Description char Character array (string) complex Complex data. Cast function takes real and imaginary components double Double-precision floating point int8, int16, int32, int64 Signed integer logical Boolean true or false single Single-precision floating point struct Structure uint8, uint16, uint32, uint64 Unsigned integer Fixed-point See “Fixed-Point Data Types”. 5-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-18 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6 Defining Data for Code Generation • “Data Definition for Code Generation” on page 6-2 • “Code Generation for Complex Data” on page 6-4 • “Code Generation for Characters” on page 6-6 • “Array Size Restrictions for Code Generation” on page 6-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6 Defining Data for Code Generation Data Definition for Code Generation To generate efficient standalone code, you must define the following types and classes of data differently than you normally would when running your code in the MATLAB environment: Data What's Different More Information Arrays Maximum number of elements is restricted “Array Size Restrictions for Code Generation” on page 6-7 Complex numbers • Complexity of variables must be set at time of assignment and before first use “Code Generation for Complex Data” on page 6-4 • Expressions containing a complex number or variable evaluate to a complex result, even if the result is zero Note: Because MATLAB does not support complex integer arithmetic, you cannot generate code for functions that use complex integer arithmetic Characters Restricted to 8 bits of precision “Code Generation for Characters” on page 6-6 Enumerated data • Supports integer-based enumerated types only “Enumerated Data” • Restricted use in switch statements and for-loops Function handles • Same bound variable cannot reference 6-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان “Function Handles” Data Definition for Code Generation Data What's Different different function handles More Information • Cannot pass function handles to or from primary or extrinsic functions • Cannot view function handles from the debugger 6-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6 Defining Data for Code Generation Code Generation for Complex Data In this section... “Restrictions When Defining Complex Variables” on page 6-4 “Expressions With Complex Operands Yield Complex Results” on page 6-4 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 Expressions With Complex Operands Yield Complex Results In general, expressions that contain one or more complex operands produce a complex result in generated code, even if the value of the result is zero. Consider the following example: x = 2 + 3i; 6-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Code Generation for Complex Data y = 2 - 3i; z = x + y; % z is 4 + 0i. In MATLAB, this code generates the real result z = 4. 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. z equals the complex result 4 + 0i in generated code, not 4 as in MATLAB code. Exceptions to this behavior are: • Values returned by MEX functions are real when the imaginary part of the value is zero. function y = foo() y = 1 + 0i; % y is complex with imaginary part equal to zero end The MEX function foo_mex returns the real value 1. z = foo_mex • Complex arguments to extrinsic functions are real when the imaginary part of the argument is zero. function y = foo() coder.extrinsic('sqrt') x = 1 + 0i; % x is complex y = sqrt(x); % x is real, y is real end • Functions that take complex arguments but produce real results return real values. 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 return complex values. z = complex(x,y); % z is a complex number for a real x and y. 6-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6 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. 6-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Array Size Restrictions for Code Generation Array Size Restrictions for Code Generation For code generation, the maximum number of elements of an array is constrained by the code generation software and the target hardware. For fixed-size arrays and variable-size arrays that use static memory allocation, the maximum number of elements is the smaller of: • intmax('int32'). • The largest integer that fits in the C int data type on the target hardware. For variable-size arrays that use dynamic memory allocation, the maximum number of elements is the smaller of: • intmax('int32'). • The largest power of 2 that fits in the C int data type on the target hardware. These restrictions apply even on a 64-bit platform. For a fixed-size array, if the number of elements exceeds the maximum, the code generation software reports an error at compile time. For a variable-size array, if the number of elements exceeds the maximum during execution of the generated MEX in MATLAB, the MEX code reports an error. Generated standalone code cannot report array size violations. See Also • “Variable-Size Data” • coder.HardwareImplementation 6-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-8 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data • “What Is Variable-Size Data?” on page 7-2 • “Variable-Size Data Definition for Code Generation” on page 7-3 • “Bounded Versus Unbounded Variable-Size Data” on page 7-4 • “Control Memory Allocation of Variable-Size Data” on page 7-5 • “Specify Variable-Size Data Without Dynamic Memory Allocation” on page 7-6 • “Variable-Size Data in Code Generation Reports” on page 7-9 • “Define Variable-Size Data for Code Generation” on page 7-11 • “C Code Interface for Arrays” on page 7-17 • “Diagnose and Fix Variable-Size Data Errors” on page 7-21 • “Incompatibilities with MATLAB in Variable-Size Support for Code Generation” on page 7-25 • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” on page 7-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data What Is Variable-Size Data? Variable-size data is data whose size can change at run time. By contrast, fixed-size data is data whose size is known and locked at compile time and, therefore, cannot change at run time. For example, in the following MATLAB function nway, B is a variable-size array; its length is not known at compile time. function B = nway(A,n) % Compute average of every N elements of A and put them in B. if ((mod(numel(A),n) == 0) && (n>=1 && n<=numel(A))) B = ones(1,numel(A)/n); k = 1; for i = 1 : numel(A)/n B(i) = mean(A(k + (0:n-1))); k = k + n; end else error('n <= 0 or does not divide number of elements evenly'); end 7-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Variable-Size Data Definition for Code Generation Variable-Size Data Definition for Code Generation In the MATLAB language, data can vary in size. By contrast, the semantics of generated code constrains the class, complexity, and shape of every expression, variable, and structure field. Therefore, for code generation, you must use each variable consistently. Each variable must: • Be either complex or real (determined at first assignment) • Have a consistent shape For fixed-size data, the shape is the same as the size returned in MATLAB. For example, if size(A) == [4 5], the shape of variable A is 4 x 5. For variable-size data, the shape can be abstract. That is, one or more dimensions can be unknown (such as 4x? or ?x?). By default, the compiler detects code logic that attempts to change these fixed attributes after initial assignments, and flags these occurrences as errors during code generation. However, you can override this behavior by defining variables or structure fields as variable-size data. For more information, see “Bounded Versus Unbounded Variable-Size Data” on page 7-4 7-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Bounded Versus Unbounded Variable-Size Data You can generate code for bounded and unbounded variable-size data. Bounded variablesize data has fixed upper bounds; this data can be allocated statically on the stack or dynamically on the heap. Unbounded variable-size data does not have fixed upper bounds; this data must be allocated on the heap. If you use unbounded data, you must use dynamic memory allocation so that the compiler: • Does not check for upper bounds • Allocates memory on the heap instead of the stack You can control the memory allocation of variable-size data. For more information, see “Control Memory Allocation of Variable-Size Data” on page 7-5. 7-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Control Memory Allocation of Variable-Size Data Control Memory Allocation of Variable-Size Data Data whose size (in bytes) is greater than or equal to the dynamic memory allocation threshold is allocated on the heap. The default dynamic memory allocation threshold is 64 kilobytes. Data whose size is less than this threshold is allocated on the stack. Dynamic memory allocation is an expensive operation; the performance cost might be too high for small data sets. If you use small variable-size data sets or data that does not change size at run time, disable dynamic memory allocation. See “Control Dynamic Memory Allocation”. You can control memory allocation globally for your application by modifying the dynamic memory allocation threshold. See “Generate Code for a MATLAB Function That Expands a Vector in a Loop”. You can control memory allocation for individual variables by specifying upper bounds. See “Specifying Upper Bounds for Variable-Size Data” on page 7-6. 7-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Specify Variable-Size Data Without Dynamic Memory Allocation In this section... “Fixing Upper Bounds Errors” on page 7-6 “Specifying Upper Bounds for Variable-Size Data” on page 7-6 Fixing Upper Bounds Errors If MATLAB cannot determine or compute the upper bound, you must specify an upper bound. See “Specifying Upper Bounds for Variable-Size Data” on page 7-6 and “Diagnosing and Fixing Errors in Detecting Upper Bounds” on page 7-23 Specifying Upper Bounds for Variable-Size Data • “When to Specify Upper Bounds for Variable-Size Data” on page 7-6 • “Specifying Upper Bounds on the Command Line for Variable-Size Inputs” on page 7-6 • “Specifying Unknown Upper Bounds for Variable-Size Inputs” on page 7-7 • “Specifying Upper Bounds for Local Variable-Size Data” on page 7-7 • “Using a Matrix Constructor with Nonconstant Dimensions” on page 7-8 When to Specify Upper Bounds for Variable-Size Data When using static allocation on the stack during code generation, MATLAB must be able to determine upper bounds for variable-size data. Specify the upper bounds explicitly for variable-size data from external sources, such as inputs and outputs. Specifying Upper Bounds on the Command Line for Variable-Size Inputs Use the coder.typeof construct with the -args option on the codegen command line (requires a MATLAB Coder license). For example: codegen foo -args {coder.typeof(double(0),[3 100],1)} This command specifies that the input to function foo is a matrix of real doubles with two variable dimensions. The upper bound for the first dimension is 3; the upper bound for the second dimension is 100. For a detailed explanation of this syntax, see coder.typeof. 7-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Variable-Size Data Without Dynamic Memory Allocation Specifying Unknown Upper Bounds for Variable-Size Inputs If you use dynamic memory allocation, you can specify that you don't know the upper bounds of inputs. To specify an unknown upper bound, use the infinity constant Inf in place of a numeric value. For example: codegen foo -args {coder.typeof(double(0), [1 Inf])} In this example, the input to function foo is a vector of real doubles without an upper bound. Specifying Upper Bounds for Local Variable-Size Data When using static allocation, MATLAB uses a sophisticated analysis to calculate the upper bounds of local data at compile time. However, when the analysis fails to detect an upper bound or calculates an upper bound that is not precise enough for your application, you need to specify upper bounds explicitly for local variables. You do not need to specify upper bounds when using dynamic allocation on the heap. In this case, MATLAB assumes variable-size data is unbounded and does not attempt to determine upper bounds. Constraining the Value of a Variable That Specifies Dimensions of Variable-Size Data Use the assert function with relational operators to constrain the value of variables that specify the dimensions of variable-size data. For example: function y = dim_need_bound(n) %#codegen assert (n <= 5); L= ones(n,n); M = zeros(n,n); M = [L; M]; y = M; This assert statement constrains input n to a maximum size of 5, defining L and M as variable-sized matrices with upper bounds of 5 for each dimension. Specifying the Upper Bounds for All Instances of a Local Variable Use the coder.varsize function to specify the upper bounds for all instances of a local variable in a function. For example: function Y = example_bounds1(u) %#codegen Y = [1 2 3 4 5]; 7-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data coder.varsize('Y', [1 10]); if (u > 0) Y = [Y Y+u]; else Y = [Y Y*u]; end The second argument of coder.varsize specifies the upper bound for each instance of the variable specified in the first argument. In this example, the argument [1 10] indicates that for every instance of Y: • First dimension is fixed at size 1 • Second dimension can grow to an upper bound of 10 By default, coder.varsize assumes dimensions of 1 are fixed size. For more information, see the coder.varsize reference page. Using a Matrix Constructor with Nonconstant Dimensions You can define a variable-size matrix by using a constructor with nonconstant dimensions. For example: function y = var_by_assign(u) %#codegen if (u > 0) y = ones(3,u); else y = zeros(3,1); end If you are not using dynamic memory allocation, you must also add an assert statement to provide upper bounds for the dimensions. For example: function y = var_by_assign(u) %#codegen assert (u < 20); if (u > 0) y = ones(3,u); else y = zeros(3,1); end 7-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Variable-Size Data in Code Generation Reports Variable-Size Data in Code Generation Reports In this section... “What Reports Tell You About Size” on page 7-9 “How Size Appears in Code Generation Reports” on page 7-10 “How to Generate a Code Generation Report” on page 7-10 What Reports Tell You About Size Code generation reports: • Differentiate fixed-size from variable-size data • Identify variable-size data with unknown upper bounds • Identify variable-size data with fixed dimensions If you define a variable-size array and then subsequently fix the dimensions of this array in the code, the report appends * to the size of the variable. In the generated C code, this variable appears as a variable-size array, but the size of its dimensions does not change during execution. • Provide guidance on how to fix size mismatch and upper bounds errors. 7-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data How Size Appears in Code Generation Reports :? means variable size, unknown upper bound No colon prefix (:) means fixed size :100 means variable size, upper bound = 100 * means that you declared y as variable size, but subsequently fixed its dimensions How to Generate a Code Generation Report Add the -report option to your codegen command. 7-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Variable-Size Data for Code Generation Define Variable-Size Data for Code Generation In this section... “When to Define Variable-Size Data Explicitly” on page 7-11 “Using a Matrix Constructor with Nonconstant Dimensions” on page 7-11 “Inferring Variable Size from Multiple Assignments” on page 7-12 “Defining Variable-Size Data Explicitly Using coder.varsize” on page 7-13 When to Define Variable-Size Data Explicitly For code generation, you must assign variables to have a specific class, size, and complexity before using them in operations or returning them as outputs. Generally, you cannot reassign variable properties after the initial assignment. Therefore, attempts to grow a variable or structure field after assigning it a fixed size might cause a compilation error. In these cases, you must explicitly define the data as variable sized using one of these methods: Method See Assign the data from a variable-size matrix “Using a Matrix Constructor with constructor such as Nonconstant Dimensions” on page 7-11 • ones • zeros • repmat Assign multiple, constant sizes to the same variable before using (reading) the variable. “Inferring Variable Size from Multiple Assignments” on page 7-12 Define all instances of a variable to be variable sized “Defining Variable-Size Data Explicitly Using coder.varsize” on page 7-13 Using a Matrix Constructor with Nonconstant Dimensions You can define a variable-size matrix by using a constructor with nonconstant dimensions. For example: 7-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data function y = var_by_assign(u) %#codegen if (u > 0) y = ones(3,u); else y = zeros(3,1); end If you are not using dynamic memory allocation, you must also add an assert statement to provide upper bounds for the dimensions. For example: function y = var_by_assign(u) %#codegen assert (u < 20); if (u > 0) y = ones(3,u); else y = zeros(3,1); end Inferring Variable Size from Multiple Assignments You can define variable-size data by assigning multiple, constant sizes to the same variable before you use (read) the variable in your code. When MATLAB uses static allocation on the stack for code generation, it infers the upper bounds from the largest size specified for each dimension. When you assign the same size to a given dimension across all assignments, MATLAB assumes that the dimension is fixed at that size. The assignments can specify different shapes as well as sizes. When dynamic memory allocation is used, MATLAB does not check for upper bounds; it assumes variable-size data is unbounded. Inferring Upper Bounds from Multiple Definitions with Different Shapes function y = var_by_multiassign(u) %#codegen if (u > 0) y = ones(3,4,5); else y = zeros(3,1); end When static allocation is used, this function infers that y is a matrix with three dimensions, where: • First dimension is fixed at size 3 7-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Variable-Size Data for Code Generation • Second dimension is variable with an upper bound of 4 • Third dimension is variable with an upper bound of 5 The code generation report represents the size of matrix y like this: When dynamic allocation is used, the function analyzes the dimensions of y differently: • First dimension is fixed at size 3 • Second and third dimensions are unbounded In this case, the code generation report represents the size of matrix y like this: Defining Variable-Size Data Explicitly Using coder.varsize Use the function coder.varsize to define one or more variables or structure fields as variable-size data. Optionally, you can also specify which dimensions vary along with their upper bounds (see “Specifying Which Dimensions Vary” on page 7-14). For example: • Define B as a variable-size 2-by-2 matrix, where each dimension has an upper bound of 64: coder.varsize('B', [64 64]); • Define B as a variable-size matrix: coder.varsize('B'); When you supply only the first argument, coder.varsize assumes all dimensions of B can vary and that the upper bound is size(B). 7-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data For more information, see the coder.varsize reference page. Specifying Which Dimensions Vary You can use the function coder.varsize to specify which dimensions vary. For example, the following statement defines B as a row vector whose first dimension is fixed at 2, but whose second dimension can grow to an upper bound of 16: coder.varsize('B', [2, 16], [0 1]) The third argument specifies which dimensions vary. This argument must be a logical vector or a double vector containing only zeros and ones. Dimensions that correspond to zeros or false have fixed size; dimensions that correspond to ones or true vary in size. coder.varsize usually treats dimensions of size 1 as fixed (see “Defining Variable-Size Matrices with Singleton Dimensions” on page 7-14). For more information about the syntax, see the coder.varsize reference page. Allowing a Variable to Grow After Defining Fixed Dimensions Function var_by_if defines matrix Y with fixed 2-by-2 dimensions before first use (where the statement Y = Y + u reads from Y). However, coder.varsize defines Y as a variable-size matrix, allowing it to change size based on decision logic in the else clause: function Y = var_by_if(u) %#codegen if (u > 0) Y = zeros(2,2); coder.varsize('Y'); if (u < 10) Y = Y + u; end else Y = zeros(5,5); end Without coder.varsize, MATLAB infers Y to be a fixed-size, 2-by-2 matrix and generates a size mismatch error during code generation. Defining Variable-Size Matrices with Singleton Dimensions A singleton dimension is a dimension for which size(A,dim) = 1. Singleton dimensions are fixed in size when: 7-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Variable-Size Data for Code Generation • You specify a dimension with an upper bound of 1 in coder.varsize expressions. For example, in this function, Y behaves like a vector with one variable-size dimension: function Y = dim_singleton(u) %#codegen Y = [1 2]; coder.varsize('Y', [1 10]); if (u > 0) Y = [Y 3]; else Y = [Y u]; end • You initialize variable-size data with singleton dimensions using matrix constructor expressions or matrix functions. For example, in this function, both X and Y behave like vectors where only their second dimensions are variable sized: function [X,Y] = dim_singleton_vects(u) %#codegen Y = ones(1,3); X = [1 4]; coder.varsize('Y','X'); if (u > 0) Y = [Y u]; else X = [X u]; end You can override this behavior by using coder.varsize to specify explicitly that singleton dimensions vary. For example: function Y = dim_singleton_vary(u) %#codegen Y = [1 2]; coder.varsize('Y', [1 10], [1 1]); if (u > 0) Y = [Y Y+u]; else Y = [Y Y*u]; end In this example, the third argument of coder.varsize is a vector of ones, indicating that each dimension of Y varies in size. For more information, see the coder.varsize reference page. 7-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Defining Variable-Size Structure Fields To define structure fields as variable-size arrays, use colon (:) as the index expression. The colon (:) indicates that all elements of the array are variable sized. For example: function y=struct_example() %#codegen d = struct('values', zeros(1,0), 'color', 0); data = repmat(d, [3 3]); coder.varsize('data(:).values'); for i = 1:numel(data) data(i).color = rand-0.5; data(i).values = 1:i; end y = 0; for i = 1:numel(data) if data(i).color > 0 y = y + sum(data(i).values); end; end The expression coder.varsize('data(:).values') defines the field values inside each element of matrix data to be variable sized. Here are other examples: • coder.varsize('data.A(:).B') In this example, data is a scalar variable that contains matrix A. Each element of matrix A contains a variable-size field B. • coder.varsize('data(:).A(:).B') This expression defines field B inside each element of matrix A inside each element of matrix data to be variable sized. 7-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان C Code Interface for Arrays C Code Interface for Arrays In this section... “C Code Interface for Statically Allocated Arrays” on page 7-17 “C Code Interface for Dynamically Allocated Arrays” on page 7-18 “Utility Functions for Creating emxArray Data Structures” on page 7-19 C Code Interface for Statically Allocated Arrays In generated code, MATLAB contains two pieces of information about statically allocated arrays: the maximum size of the array and its actual size. For example, consider the MATLAB function uniquetol: function B = uniquetol(A, tol) %#codegen A = sort(A); coder.varsize('B'); B = A(1); k = 1; for i = 2:length(A) if abs(A(k) - A(i)) > tol B = [B A(i)]; k = i; end end Generate code for uniquetol specifying that input A is a variable-size real double vector whose first dimension is fixed at 1 and second dimension can vary up to 100 elements. codegen -config:lib -report uniquetol -args {coder.typeof(0,[1 100],1),coder.typeof(0)} In the generated code, the function declaration is: extern void uniquetol(const double A_data[100], const int A_size[2],... double tol, emxArray_real_T *B); There are two pieces of information about A: • double A_data[100]: the maximum size of input A (where 100 is the maximum size specified using coder.typeof). • int A_size[2]: the actual size of the input. 7-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data C Code Interface for Dynamically Allocated Arrays In generated code, MATLAB represents dynamically allocated data as a structure type called emxArray. An embeddable version of the MATLAB mxArray, the emxArray is a family of data types, specialized for all base types. emxArray Structure Definition typedef struct emxArray_<baseTypedef> { <baseType> *data; int *size; int allocatedSize; int numDimensions; boolean_T canFreeData; } emxArray_<baseTypedef>; where baseTypedef is the predefined type in rtwtypes.h corresponding to baseType. For example, here's the definition for an emxArray of base type double with unknown upper bounds: typedef struct emxArray_real_T { double *data; int *size; int allocatedSize; int numDimensions; boolean_T canFreeData; } emxArray_real_T; Note that the predefined type corresponding to double is real_T. For more information on the correspondence between built-in data types and predefined types in rtwtypes.h, see “How MATLAB Coder Infers C/C++ Data Types”. To define two variables, in1 and in2, of this type, use this statement: emxArray_real_T *in1, *in2; C Code Interface for Structure Fields Field Description *data Pointer to data of type <baseType> *size Pointer to first element of size vector. Length of the vector equals the number of dimensions. 7-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان C Code Interface for Arrays Field Description allocatedSize Number of elements currently allocated for the array. If the size changes, MATLAB reallocates memory based on the new size. numDimensions Number of dimensions of the size vector, that is, the number of dimensions you can access without crossing into unallocated or unused memory canFreeData Boolean flag indicating how to deallocate memory: • true – MATLAB deallocates memory automatically • false – Calling program determines when to deallocate memory Utility Functions for Creating emxArray Data Structures When you generate code that uses variable-size data, the code generation software exports a set of utility functions that you can use to create and interact with emxArrays in your generated code. To call these functions in your main C function, include the generated header file. For example, when you generate code for function foo, include foo_emxAPI.h in your main C function. For more information, see the “Write a C Main Function” section in “Using Dynamic Memory Allocation for an "Atoms" Simulation”. Note: The code generation software exports emxArray utility functions only for variablesize arrays that are entry-point function inputs or outputs. Function Arguments Description emxArray_<baseType> *emxCreateWrapper_<baseType> (...) *data num_rows num_cols Creates a new 2dimensional emxArray, but does not allocate it on the heap. Instead uses memory provided by the user and sets canFreeData to 7-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Function Arguments Description false so it does not inadvertently free user memory, such as the stack. emxArray_<baseType> *emxCreateWrapperND_<baseType> (...) *data numDimensions *size Same as emxCreateWrapper, except it creates a new N-dimensional emxArray. emxArray_<baseType> *emxCreate_<baseType> (...) num_rows num_cols Creates a new twodimensional emxArray on the heap, initialized to zero. All data elements have the data type specified by baseTypeName. emxArray_<baseType> *emxCreateND_<baseType> (...) numDimensions *size Same as emxCreate, except it creates a new N-dimensional emxArray on the heap. emxArray_<baseType> *emxArray *emxDestroyArray_<baseType> (...) 7-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Frees dynamic memory allocated by *emxCreate and *emxCreateND functions. Diagnose and Fix Variable-Size Data Errors Diagnose and Fix Variable-Size Data Errors In this section... “Diagnosing and Fixing Size Mismatch Errors” on page 7-21 “Diagnosing and Fixing Errors in Detecting Upper Bounds” on page 7-23 Diagnosing and Fixing Size Mismatch Errors Check your code for these issues: Assigning Variable-Size Matrices to Fixed-Size Matrices You cannot assign variable-size matrices to fixed-size matrices in generated code. Consider this example: function Y = example_mismatch1(n) %#codegen assert(n<10); B = ones(n,n); A = magic(3); A(1) = mean(A(:)); if (n == 3) A = B; end Y = A; Compiling this function produces this error: ??? Dimension 1 is fixed on the left-hand side but varies on the right ... There are several ways to fix this error: • Allow matrix A to grow by adding the coder.varsize construct: function Y = example_mismatch1_fix1(n) %#codegen coder.varsize('A'); assert(n<10); B = ones(n,n); A = magic(3); 7-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data A(1) = mean(A(:)); if (n == 3) A = B; end Y = A; • Explicitly restrict the size of matrix B to 3-by-3 by modifying the assert statement: function Y = example_mismatch1_fix2(n) %#codegen coder.varsize('A'); assert(n==3) B = ones(n,n); A = magic(3); A(1) = mean(A(:)); if (n == 3) A = B; end Y = A; • Use explicit indexing to make B the same size as A: function Y = example_mismatch1_fix3(n) %#codegen assert(n<10); B = ones(n,n); A = magic(3); A(1) = mean(A(:)); if (n == 3) A = B(1:3, 1:3); end Y = A; Empty Matrix Reshaped to Match Variable-Size Specification If you assign an empty matrix [] to variable-size data, MATLAB might silently reshape the data in generated code to match a coder.varsize specification. For example: function Y = test(u) %#codegen Y = []; coder.varsize(‘Y’, [1 10]); If u < 0 Y = [Y u]; end 7-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Performing Binary Operations on Fixed and Variable-Size Operands In this example, coder.varsize defines Y as a column vector of up to 10 elements, so its first dimension is fixed at size 1. The statement Y = [] designates the first dimension of Y as 0, creating a mismatch. The right hand side of the assignment is an empty matrix and the left hand side is a variable-size vector. In this case, MATLAB reshapes the empty matrix Y = [] in generated code to Y = zeros(1,0) so it matches the coder.varsize specification. Performing Binary Operations on Fixed and Variable-Size Operands You cannot perform binary operations on operands of different sizes. Operands have different sizes if one has fixed dimensions and the other has variable dimensions. For example: function z = mismatch_operands(n) %#codegen assert(n>=3 && n<10); x = ones(n,n); y = magic(3); z = x + y; When you compile this function, you get an error because y has fixed dimensions (3 x 3), but x has variable dimensions. Fix this problem by using explicit indexing to make x the same size as y: function z = mismatch_operands_fix(n) %#codegen assert(n>=3 && n<10); x = ones(n,n); y = magic(3); z = x(1:3,1:3) + y; Diagnosing and Fixing Errors in Detecting Upper Bounds Check your code for these issues: Using Nonconstant Dimensions in a Matrix Constructor You can define variable-size data by assigning a variable to a matrix with nonconstant dimensions. For example: 7-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data function y = dims_vary(u) %#codegen if (u > 0) y = ones(3,u); else y = zeros(3,1); end However, compiling this function generates an error because you did not specify an upper bound for u. There are several ways to fix the problem: • Enable dynamic memory allocation and recompile. During code generation, MATLAB does not check for upper bounds when it uses dynamic memory allocation for variablesize data. • If you do not want to use dynamic memory allocation, add an assert statement before the first use of u: function y = dims_vary_fix(u) %#codegen assert (u < 20); if (u > 0) y = ones(3,u); else y = zeros(3,1); end 7-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Incompatibilities with MATLAB in Variable-Size Support for Code Generation Incompatibilities with MATLAB in Variable-Size Support for Code Generation In this section... “Incompatibility with MATLAB for Scalar Expansion” on page 7-25 “Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays” on page 7-27 “Incompatibility with MATLAB in Determining Size of Empty Arrays” on page 7-28 “Incompatibility with MATLAB in Determining Class of Empty Arrays” on page 7-29 “Incompatibility with MATLAB in Vector-Vector Indexing” on page 7-30 “Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation” on page 7-30 “Incompatibility with MATLAB in Concatenating Variable-Size Matrices” on page 7-31 “Dynamic Memory Allocation Not Supported for MATLAB Function Blocks” on page 7-32 Incompatibility with MATLAB for Scalar Expansion Scalar expansion is a method of converting scalar data to match the dimensions of vector or matrix data. Except for some matrix operators, MATLAB arithmetic operators work on corresponding elements of arrays with equal dimensions. For vectors and rectangular arrays, both operands must be the same size unless one is a scalar. If one operand is a scalar and the other is not, MATLAB applies the scalar to every element of the other operand—this property is known as scalar expansion. During code generation, the standard MATLAB scalar expansion rules apply except when operating on two variable-size expressions. In this case, both operands must be the same size. The generated code does not perform scalar expansion even if one of the variable-size expressions turns out to be scalar at run time. Instead, it generates a size mismatch error at run time for MEX functions. Run-time error checking does not occur for non-MEX builds; the generated code will have unspecified behavior. For example, in the following function, z is scalar for the switch statement case 0 and case 1. MATLAB applies scalar expansion when evaluating y(:) = z; for these two cases. 7-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data function y = scalar_exp_test_err1(u) %#codegen y = ones(3); switch u case 0 z = 0; case 1 z = 1; otherwise z = zeros(3); end y(:) = z; When you generate code for this function, the code generation software determines that z is variable size with an upper bound of 3. If you run the MEX function with u equal to zero or one, even though z is scalar at run time, the generated code does not perform scalar expansion and a run-time error occurs. scalar_exp_test_err1_mex(0) Sizes mismatch: 9 ~= 1. Error in scalar_exp_test_err1 (line 11) y(:) = z; Workaround Use indexing to force z to be a scalar value: 7-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Incompatibilities with MATLAB in Variable-Size Support for Code Generation function y = scalar_exp_test_err1(u) %#codegen y = ones(3); switch u case 0 z = 0; case 1 z = 1; otherwise z = zeros(3); end y(:) = z(1); Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays For variable-size N-D arrays, the size function can return a different result in generated code than in MATLAB. In generated code, size(A) returns a fixed-length output because it does not drop trailing singleton dimensions of variable-size N-D arrays. By contrast, size(A) in MATLAB returns a variable-length output because it drops trailing singleton dimensions. For example, if the shape of array A is :?x:?x:? and size(A,3)==1, size(A) returns: • Three-element vector in generated code • Two-element vector in MATLAB code Workarounds If your application requires generated code to return the same size of variable-size N-D arrays as MATLAB code, consider one of these workarounds: • Use the two-argument form of size. For example, size(A,n) returns the same answer in generated code and MATLAB code. • Rewrite size(A): B = size(A); X = B(1:ndims(A)); 7-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data This version returns X with a variable-length output. However, you cannot pass a variable-size X to matrix constructors such as zeros that require a fixed-size argument. Incompatibility with MATLAB in Determining Size of Empty Arrays The size of an empty array in generated code might be different from its size in MATLAB source code. The size might be 1x0 or 0x1 in generated code, but 0x0 in MATLAB. Therefore, you should not write code that relies on the specific size of empty matrices. For example, consider the following code: function y = foo(n) %#codegen x = []; i=0; while (i<10) x = [5, x]; i=i+1; end if n > 0 x = []; end y=size(x); end Concatenation requires its operands to match on the size of the dimension that is not being concatenated. In the preceding concatenation the scalar value has size 1x1 and x has size 0x0. To support this use case, the code generation software determines the size for x as [1 x :?]. Because there is another assignment x = [] after the concatenation, the size of x in the generated code is 1x0 instead of 0x0. Workaround If your application checks whether a matrix is empty, use one of these workarounds: • Rewrite your code to use the isempty function instead of the size function. • Instead of using x=[] to create empty arrays, create empty arrays of a specific size using zeros. For example: function y = test_empty(n) %#codegen x = zeros(1,0); 7-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Incompatibilities with MATLAB in Variable-Size Support for Code Generation i=0; while (i<10) x = [5, x]; i=i+1; end if n > 0 x = zeros(1,0); end y=size(x); end Incompatibility with MATLAB in Determining Class of Empty Arrays The class of an empty array in generated code can be different from its class in MATLAB source code. Therefore, do not write code that relies on the class of empty matrices. For example, consider the following code: function y = fun(n) x = []; if n > 1 x = ['a', x]; end y=class(x); end fun(0) returns double in MATLAB, but char in the generated code. When the statement n > 1 is false, MATLAB does not execute x = ['a', x]. The class of x is double, the class of the empty array. However, the code generation software considers all execution paths. It determines that based on the statement x = ['a', x], the class of x is char. Workaround Instead of using x=[] to create an empty array, create an empty array of a specific class. For example, use blanks(0) to create an empty array of characters. function y = fun(n) x = blanks(0); if n > 1 x = ['a', x]; end y=class(x); end 7-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Incompatibility with MATLAB in Vector-Vector Indexing In vector-vector indexing, you use one vector as an index into another vector. When either vector is variable sized, you might get a run-time error during code generation. Consider the index expression A(B). The general rule for indexing is that size(A(B)) == size(B). However, when both A and B are vectors, MATLAB applies a special rule: use the orientation of A as the orientation of the output. For example, if size(A) == [1 5] and size(B) == [3 1], then size(A(B)) == [1 3]. In this situation, if the code generation software detects that both A and B are vectors at compile time, it applies the special rule and gives the same result as MATLAB. However, if either A or B is a variable-size matrix (has shape ?x?) at compile time, the code generation software applies only the general indexing rule. Then, if both A and B become vectors at run time, the code generation software reports a run-time error when you run the MEX function. Run-time error checking does not occur for non-MEX builds; the generated code will have unspecified behavior. It is best practice to generate and test a MEX function before generating C code. Workaround Force your data to be a vector by using the colon operator for indexing: A(B(:)). For example, suppose your code intentionally toggles between vectors and regular matrices at run time. You can do an explicit check for vector-vector indexing: ... if isvector(A) && isvector(B) C = A(:); D = C(B(:)); else D = A(B); end ... The indexing in the first branch specifies that C and B(:) are compile-time vectors. As a result, the code generation software applies the standard vector-vector indexing rule. Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation The following limitation applies to matrix indexing operations for code generation: 7-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Incompatibilities with MATLAB in Variable-Size Support for Code Generation • Initialization of the following style: for i = 1:10 M(i) = 5; end In this case, the size of M changes as the loop is executed. Code generation does not support increasing the size of an array over time. For code generation, preallocate M as highlighted in the following code. M=zeros(1,10); for i = 1:10 M(i) = 5; end The following limitation applies to matrix indexing operations for code generation when dynamic memory allocation is disabled: • M(i:j) where i and j change in a loop During code generation, memory is not dynamically allocated for the size of the expressions that change as the program executes. To implement this behavior, use for-loops as shown in the following example: ... M = ones(10,10); for i=1:10 for j = i:10 M(i,j) = 2 * M(i,j); end end ... Note: The matrix M must be defined before entering the loop, as shown in the highlighted code. Incompatibility with MATLAB in Concatenating Variable-Size Matrices For code generation, when you concatenate variable-sized arrays, the dimensions that are not being concatenated must match exactly. 7-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Dynamic Memory Allocation Not Supported for MATLAB Function Blocks You cannot use dynamic memory allocation for variable-size data in MATLAB Function blocks. Use bounded instead of unbounded variable-size data. 7-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Variable-Sizing Restrictions for Code Generation of Toolbox Functions Variable-Sizing Restrictions for Code Generation of Toolbox Functions In this section... “Common Restrictions” on page 7-33 “Toolbox Functions with Variable Sizing Restrictions” on page 7-34 Common Restrictions The following common restrictions apply to multiple toolbox functions, but only for code generation. To determine which of these restrictions apply to specific library functions, see the table in “Toolbox Functions with Variable Sizing Restrictions” on page 7-34. Variable-length vector restriction Inputs to the library function must be variable-length vectors or fixed-size vectors. A variable-length vector is a variable-size array that has the shape 1x:n or :nx1 (one dimension is variable sized and the other is fixed at size 1). Other shapes are not permitted, even if they are vectors at run time. Automatic dimension restriction When the function selects the working dimension automatically, it bases the selection on the upper bounds for the dimension sizes. In the case of the sum function, sum(X) selects its working dimension automatically, while sum(X, dim) uses dim as the explicit working dimension. For example, if X is a variable-size matrix with dimensions 1x:3x:5, sum(x) behaves like sum(X,2) in generated code. In MATLAB, it behaves like sum(X,2) provided size(X,2) is not 1. In MATLAB, when size(X,2) is 1, sum(X) behaves like sum(X,3). Consequently, you get a run-time error if an automatically selected working dimension assumes a length of 1 at run time. To avoid the issue, specify the intended working dimension explicitly as a constant value. Array-to-vector restriction The function issues an error when a variable-size array that is not a variable-length vector assumes the shape of a vector at run time. To avoid the issue, specify the input explicitly as a variable-length vector instead of a variable-size array. 7-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Array-to-scalar restriction The function issues an error if a variable-size array assumes a scalar value at run time. To avoid this issue, specify scalars as fixed size. Toolbox Functions with Variable Sizing Restrictions The following restrictions apply to specific toolbox functions, but only for code generation. Function Restrictions with Variable-Size Data all • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass the first argument a variable-size matrix that is 0-by-0 at run time. any • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass the first argument a variable-size matrix that is 0-by-0 at run time. bsxfun • Dimensions expand only where one input array or the other has a fixed length of 1. cat • Dimension argument must be a constant. • An error occurs if variable-size inputs are empty at run time. conv • See “Variable-length vector restriction” on page 7-33. • Input vectors must have the same orientation, either both row vectors or both column vectors. cov • For cov(X), see“Array-to-vector restriction” on page 7-33. cross • Variable-size array inputs that become vectors at run time must have the same orientation. deconv • For both arguments, see“Variable-length vector restriction” on page 7-33. detrend • For first argument for row vectors only, see “Array-tovector restriction” on page 7-33 . diag • See “Array-to-vector restriction” on page 7-33 . diff • See “Automatic dimension restriction” on page 7-33. 7-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Variable-Sizing Restrictions for Code Generation of Toolbox Functions Function Restrictions with Variable-Size Data • Length of the working dimension must be greater than the difference order input when the input is variable sized. For example, if the input is a variable-size matrix that is 3-by-5 at run time, diff(x,2,1) works but diff(x,5,1) generates a run-time error. fft • See “Automatic dimension restriction” on page 7-33. filter • For first and second arguments, see “Variable-length vector restriction” on page 7-33. • See “Automatic dimension restriction” on page 7-33. hist • For second argument, see “Variable-length vector restriction” on page 7-33. • For second input argument, see“Array-to-scalar restriction” on page 7-34. histc • See “Automatic dimension restriction” on page 7-33. ifft • See “Automatic dimension restriction” on page 7-33. ind2sub • First input (the size vector input) must be fixed size. interp1 • For the Y input and xi input, see“Array-to-vector restriction” on page 7-33. • Y input can become a column vector dynamically. • A run-time error occurs if Y input is not a variablelength vector and becomes a row vector at run time. ipermute • Order input must be fixed size. issorted • For optional rows input, see “Variable-length vector restriction” on page 7-33. magic • Argument must be a constant. • Output can be fixed-size matrices only. max • See “Automatic dimension restriction” on page 7-33. mean • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass as the first argument a variable-size matrix that is 0-by-0 at run time. 7-35 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Function Restrictions with Variable-Size Data median • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass as the first argument a variable-size matrix that is 0-by-0 at run time. min • See “Automatic dimension restriction” on page 7-33. mode • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass as the first argument a variable-size matrix that is 0-by-0 at run time. mtimes • When an input is variable-size, MATLAB determines whether to generate code for a general matrix*matrix multiplication or a scalar*matrix multiplication, based on whether one of the arguments is a fixed-size scalar. If neither argument is a fixed-size scalar, the inner dimensions of the two arguments must agree even if a variable-size matrix input is a scalar at run time. nchoosek • The second input, k, must be a fixed-size scalar. • The second input, k, must be a constant for static allocation. If you enable dynamic allocation, the second input can be a variable. • You cannot create a variable-size array by passing in a variable, k, unless you enable dynamic allocation. permute • Order input must be fixed-size. planerot • Input must be a fixed-size, two-element column vector. It cannot be a variable-size array that takes on the size 2-by-1 at run time. poly • See “Variable-length vector restriction” on page 7-33. polyfit • For first and second arguments, see “Variable-length vector restriction” on page 7-33. prod • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass as the first argument a variable-size matrix that is 0-by-0 at run time. 7-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Variable-Sizing Restrictions for Code Generation of Toolbox Functions Function Restrictions with Variable-Size Data rand • For an upper-bounded variable N, rand(1,N) produces a variable-length vector of 1x:M where M is the upper bound on N. • For an upper-bounded variable N, rand([1,N]) may produce a variable-length vector of :1x:M where M is the upper bound on N. Generated fixed-point code • For an upper-bounded variable N, randn(1,N) produces enhancements a variable-length vector of 1x:M where M is the upper bound on N. • For an upper-bounded variable N, randn([1,N]) may produce a variable-length vector of :1x:M where M is the upper bound on N. Generated fixed-point code • For an upper-bounded variable N, randn(1,N) produces enhancements a variable-length vector of 1x:M where M is the upper bound on N. • For an upper-bounded variable N, randn([1,N]) may produce a variable-length vector of :1x:M where M is the upper bound on N. reshape • If the input is a variable-size array and the output array has at least one fixed-length dimension, do not specify the output dimension sizes in a size vector sz. Instead, specify the output dimension sizes as scalar values, sz1,...,szN. Specify fixed-size dimensions as constants. • When the input is a variable-size empty array, the maximum dimension size of the output array (also empty) cannot be larger than that of the input. roots • See “Variable-length vector restriction” on page 7-33. 7-37 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Code Generation for Variable-Size Data Function Restrictions with Variable-Size Data shiftdim • If you do not supply the second argument, the number of shifts is determined at compilation time by the upper bounds of the dimension sizes. Consequently, at run time the number of shifts is constant. • An error occurs if the dimension that is shifted to the first dimension has length 1 at run time. To avoid the error, supply the number of shifts as the second input argument (must be a constant). • First input argument must have the same number of dimensions when you supply a positive number of shifts. std • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass a variable-size matrix with 0-by-0 dimensions at run time. sub2ind • First input (the size vector input) must be fixed size. sum • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass as the first argument a variable-size matrix that is 0-by-0 at run time. trapz • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass as the first argument a variable-size matrix that is 0-by-0 at run time. typecast • See “Variable-length vector restriction” on page 7-33 on first argument. var • See “Automatic dimension restriction” on page 7-33. • An error occurs if you pass a variable-size matrix with 0-by-0 dimensions at run time. 7-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures • “Structure Definition for Code Generation” on page 8-2 • “Structure Operations Allowed for Code Generation” on page 8-3 • “Define Scalar Structures for Code Generation” on page 8-4 • “Define Arrays of Structures for Code Generation” on page 8-7 • “Make Structures Persistent” on page 8-9 • “Index Substructures and Fields” on page 8-10 • “Assign Values to Structures and Fields” on page 8-12 • “Pass Structure Arguments by Reference or by Value” on page 8-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures Structure Definition 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 More Information Use a restricted set of operations. “Structure Operations Allowed for Code Generation” on page 8-3 Observe restrictions on properties and values of scalar structures. “Define Scalar Structures for Code Generation” on page 8-4 Make structures uniform in arrays. “Define Arrays of Structures for Code Generation” on page 8-7 Reference structure fields individually during indexing. “Index Substructures and Fields” on page 8-10 Avoid type mismatch when assigning values to structures and fields. “Assign Values to Structures and Fields” on page 8-12 8-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 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 local functions 8-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures Define Scalar Structures for Code Generation In this section... “Restriction When Using struct” on page 8-4 “Restrictions When Defining Scalar Structures by Assignment” on page 8-4 “Adding Fields in Consistent Order on Each Control Flow Path” on page 8-4 “Restriction on Adding New Fields After First Use” on page 8-5 Restriction When Using struct When you use the struct function to create scalar structures for code generation, 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: function if u > 0 x.a = x.b = else x.b = y = fcn(u) %#codegen 10; 20; 30; % Generates an error (on variable x) 8-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Scalar Structures for Code Generation 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 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 ... 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 8-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures 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. 8-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Arrays of Structures for Code Generation Define Arrays of Structures for Code Generation In this section... “Ensuring Consistency of Fields” on page 8-7 “Using repmat to Define an Array of Structures with Consistent Field Properties” on page 8-7 “Defining an Array of Structures Using Concatenation” on page 8-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. Once you have created the array of structures, you can make the structure fields variable-size using coder.varsize. For more information, see “Declare a variable-size structure field.”. 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 “Define Scalar Structures for Code Generation” on page 8-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; 8-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 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”). For code generation, the structures that you concatenate must have the same size, class, and complexity. For example, the following code uses concatenation and a local function 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; ... 8-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Make Structures Persistent Make Structures Persistent To make structures persist, you define them to be persistent variables and initialize them with the isempty statement, as described in “Define and Initialize Persistent Variables” on page 5-10. For example, the following function defines structure X to be persistent and initializes its fields a and b: function f(u) persistent X %#codegen if isempty(X) X.a = 1; X.b = 2; end 8-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures Index 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 Symbol Resolution substruct1.a1 Field a1 of local structure substruct1 substruct2.ele3.a1 Value of field a1 of field ele3, a substructure of local structure substruct2 substruct2.ele3.a2(1,1) 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: 8-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Do not reference fields dynamically ... 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 “Define Arrays of Structures for Code Generation” on page 8-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 “Generate Field Names from Variables”). 8-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures Assign 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-tostructure assignments If: Then: Assigning one structure to another structure. Define each structure with the same number, type, and size of fields. Assigning one structure to a substructure of a different structure and vice versa. Define the structure with the same number, type, and size of fields as the substructure. Assigning an element of one structure to an The elements must have the same type and element of another structure. 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 if variable-sizing is disabled: ... Y.a = 3; Y.b = 5; X = zeros(Y.a,Y.b); % Generates an error In this example, even though you set fields a and b of structure Y to the values 3 and 5 respectively, Y.a and Y.b are not constants in generated code. Therefore, they are not valid arguments to pass to the function zeros. Note: An exception to this behavior occurs if the structure is declared completely using the struct function 8-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Do not assign mxArrays to structures ... Y = struct('a',3,'b',5); X = zeros(Y.a,Y.b); % Generates a fixed-size 3 X 5 matrix 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 13-17). 8-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures Pass Structure Arguments by Reference or by Value In this section... “Specify Pass by Reference or by Value Using a Project” on page 8-14 “Specify Pass by Reference or by Value Using the Command-Line Interface” on page 8-15 “Pass Input Structure Argument by Reference” on page 8-15 “Pass Input Structure Argument by Value” on page 8-16 “Pass Output Structure Argument by Reference” on page 8-16 “Pass Output Structure Argument by Value” on page 8-17 “Pass Input and Output Structure Argument by Reference” on page 8-18 For standalone C code generation, you can control whether a generated entry-point function passes structure arguments by reference or by value. Passing by reference uses a pointer to access the structure arguments. If the function writes to an element of the input structure, it overwrites the input value. Passing by value makes a copy of the input or output structure argument. To reduce memory usage and execution time, use pass by reference. If a structure argument is both an input and output, the generated entry-point function passes the argument by reference. Generated MEX functions pass structure arguments by reference. For MEX function output, you cannot specify that you want to pass structure arguments by value. Specify Pass by Reference or by Value Using a Project 1 On the Build tab, set the Output Type to one of the following: • C/C++ Static Library • C/C++ Dynamic Library 2 3 • C/C++ Executable To open the Project Settings dialog box, click the More settings link. On the All Settings tab, set the Pass structures by reference to entry-point functions option. 8-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Pass Structure Arguments by Reference or by Value Set To For Yes Pass by reference (default) No Pass by value Specify Pass by Reference or by Value Using the Command-Line Interface 1 Create a code configuration object for 'lib', 'dll', or 'exe': cfg = coder.config('lib'); % or dll or exe 2 Set the PassStructByReference property. Set To For true Pass by reference false Pass by value (default) For example, cfg.PassStructByReference = true; Pass Input Structure Argument by Reference This example shows how to generate an entry-point function that passes an input structure argument by reference. 1 Write the function my_struct_in. function y = my_struct_in(s) y = s.f; 2 Declare a structure variable str in the MATLAB workspace. 3 Create a code configuration object to generate a C static library. str = struct('f', 1:4); cfg = coder.config('lib'); 4 Specify that you want to pass structure arguments by reference. cfg.PassStructByReference = true; 5 Generate code. Specify that the input argument has the type of the variable str. codegen -config cfg -args {str} my_struct_in -report 8-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures 6 To view the generated C code, click View report. The generated function signature for my_struct_in is: void my_struct_in(const struct0_T *s, double y[4]) my_struct_in passes the input structure s by reference. Pass Input Structure Argument by Value This example shows how to generate an entry-point function that passes an input structure argument by value. 1 Write the function my_struct_in. function y = my_struct_in(s) y = s.f; 2 Declare a structure variable str in the MATLAB workspace. 3 Create a code configuration object to generate a C static library. str = struct('f', 1:4); cfg = coder.config('lib'); 4 Specify that you want to pass structure arguments by value. cfg.PassStructByReference = false; 5 By default, the PassStructByReference parameter is false. Generate code. Specify that the input argument has the type of the variable str. 6 To view the generated C code, click View report. codegen -config cfg -args {str} my_struct_in -report The generated function signature for my_struct_in is: void my_struct_in(const struct0_T s, double y[4]) my_struct_in passes the input structure s by value. Pass Output Structure Argument by Reference This example shows how to generate an entry-point function that passes an output structure argument by reference. 8-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Pass Structure Arguments by Reference or by Value 1 Write the function my_struct_out. function s = my_struct_out(x) s.f = x; 2 Declare a variable a in the MATLAB workspace. a = 1:4; 3 Create a code configuration object to generate a C static library. 4 Specify that you want to pass structure arguments by reference. cfg = coder.config('lib'); cfg.PassStructByReference = true; 5 Generate code. Specify that the input argument has the type of the variable a. codegen -config cfg -args {a} my_struct_out -report 6 To view the generated C code, click View report. The generated function signature for my_struct_out is: void my_struct_out(const double x[4], struct0_T *s) my_struct_out passes the output structure s by reference. Pass Output Structure Argument by Value This example shows how to generate an entry-point function that passes an output structure argument by value. 1 Write the function my_struct_out. function s = my_struct_out(x) s.f = x; 2 Declare a variable a in the MATLAB workspace. a = 1:4; 3 Create a code configuration object to generate a C static library. 4 Specify that you want to pass structure arguments by value. cfg = coder.config('lib'); cfg.PassStructByReference = false; By default, the PassStructByReference parameter is false 8-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Code Generation for MATLAB Structures 5 Generate code. Specify that the input argument has the type of the variable a. codegen -config cfg -args {a} my_struct_out -report 6 To view the generated C code, click View report. The generated function signature for my_struct_out is: struct0_T my_struct_out(const double x[4]) my_struct_out returns an output structure. Pass Input and Output Structure Argument by Reference This example shows how a generated entry-point function passes a structure argument by reference when the structure argument is both an input and an output. In this case, the function passes the structure argument by reference even though you set PassStructByReference to false. 1 Write the function my_struct_inout. function [y,s] = my_struct_inout(x,s) y = x + sum(s.f); 2 Define the variable a and structure str in the MATLAB workspace. a = 1:4; str = struct('f',a); 3 Create a code configuration object to generate a C static library. cfg = coder.config('lib'); 4 Specify that you want to pass structure arguments by value. cfg.PassStructByReference = false; 5 By default, the PassStructByReference parameter is false. Generate code. Specify that the first input has the type of a and the second input has the type of str. codegen -config cfg -args {a, str} my_struct_inout -report 6 To view the generated C code, click View report. The generated function signature for my_struct_inout is: void my_struct_inout(const double x[4], const struct0_T *s, double y[4]) 8-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Pass Structure Arguments by Reference or by Value my_struct_inout passes the structure s by reference even though PassStructByReference is false. 8-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-20 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data • “Enumerated Data Definition for Code Generation” on page 9-2 • “Enumerated Types Supported for Code Generation” on page 9-3 • “When to Use Enumerated Data for Code Generation” on page 9-6 • “Generate Code for Enumerated Data from MATLAB Algorithms” on page 9-7 • “Define Enumerated Data for Code Generation” on page 9-8 • “Operations on Enumerated Data for Code Generation” on page 9-10 • “Include Enumerated Data in Control Flow Statements” on page 9-13 • “Customize Enumerated Types for Code Generation” on page 9-19 • “Use Enumerated Types in LED Control Function” on page 9-23 • “Control Names of Enumerated Type Values in Generated Code” on page 9-26 • “Change and Reload Enumerated Data Types” on page 9-29 • “Restrictions on Use of Enumerated Data in for-Loops” on page 9-30 • “Toolbox Functions That Support Enumerated Types for Code Generation” on page 9-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Enumerated Data Definition for Code Generation To generate efficient standalone code for enumerated data, you must define and use enumerated types differently than you do in the MATLAB environment: Difference More Information Supports integer-based enumerated types only “Enumerated Types Supported for Code Generation” on page 9-3 Name of each enumerated data type must be unique “Naming Enumerated Types for Code Generation” on page 9-9 Each enumerated data type must be defined in a separate file on the MATLAB path “Define Enumerated Data for Code Generation” on page 9-8 and “Generate Code for Enumerated Data from MATLAB Algorithms” on page 9-7 Restricted set of operations “Operations on Enumerated Data for Code Generation” on page 9-10 Restricted use in for-loops “Restrictions on Use of Enumerated Data in for-Loops” on page 9-30 9-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Enumerated Types Supported for Code Generation Enumerated Types Supported for Code Generation An enumerated type is a user-defined type whose values belong to a predefined set of enumerated values. Each enumerated value consists of a name and an underlying numeric value. You define an enumerated data type in an enumeration class definition file. For code generation, you must base the class on int8, uint8, int16, uint16, or int32. For 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. PrimaryColors inherits the characteristics of the int32 type. It also defines its own unique characteristics. For example, PrimaryColors is restricted to three enumerated values: Enumerated Value Enumerated Name Underlying Numeric Value Red(1) Red 1 Blue(2) Blue 2 Yellow(4) Yellow 4 Enumeration Class Base Types for Code Generation For code generation, you must base an enumerated type on one of the following built-in MATLAB integer data types: • int8 • uint8 • int16 • uint16 9-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data • int32 You can use the base type to control the size of an enumerated type in generated C/C++ code. You can: • Represent an enumerated type as a fixed-size integer that is portable to different targets. • Reduce memory usage. • Interface to legacy code. • Match company standards. The base type determines the representation of the enumerated type in generated C/C++ code. C Code Representation for Base Type int32 If the base type is int32, the code generation software generates a C enumeration type. Consider the following MATLAB enumerated type definition: classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end end This enumerated type definition results in the following C code: enum LEDcolor { GREEN = 1, RED }; typedef enum LEDcolor LEDcolor; C Code Representation for Base Type Other Than int32 For built-in integer base types other than int32, the code generation software generates a typedef statement for the enumerated type and #define statements for the enumerated values. Consider the following MATLAB enumerated type definition: 9-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Enumerated Types Supported for Code Generation classdef(Enumeration) LEDcolor < int16 enumeration GREEN(1), RED(2) end end This enumerated type definition results in the following C code: typedef short LEDcolor; #define GREEN ((LEDcolor)1) #define RED ((LEDcolor)2) The C type in the typedef statement depends on: • The integer sizes defined for the production hardware in the Hardware Implementation object or the project settings. See coder.HardwareImplementation. • The setting that determines use of built-in C types or MathWorks typedefs in the generated code. See “Specify Data Type Used in Generated Code” and “How MATLAB Coder Infers C/C++ Data Types” . 9-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 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 restrict data to a predetermined set of values and refer to these values by name. You can sometimes achieve these goals by using integers or strings, however, enumerated types offer the following advantages: • More readable code than integers. • 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. • More efficient code than strings. For example, comparisons of enumerated values execute faster than comparisons of strings. 9-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for Enumerated Data from MATLAB Algorithms Generate Code for Enumerated Data from MATLAB Algorithms The basic workflow for generating code for enumerated types in MATLAB code is: 1 Define an enumerated data type that inherits from a base type that code generation supports. See “Enumerated Types Supported for Code Generation”. 2 Save the enumerated data type in a file on the MATLAB path. 3 Write a MATLAB function that uses the enumerated type. 4 Specify enumerated type inputs using the project or the command-line interface. 5 Generate code. See Also • “Use Enumerated Types in LED Control Function” • “Define Enumerated Data for Code Generation” • “Specifying an Enumerated Type Input Parameter by Example” • “Specifying an Enumerated Type Input Parameter by Type” 9-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Define Enumerated Data for Code Generation To define enumerated data for code generation from MATLAB algorithms: 1 Create a class definition file. In the Command Window, select File > New > Class. 2 Enter the class definition: classdef(Enumeration) EnumTypeName < BaseType EnumTypeName is a case-sensitive string that must be unique among data type names and workspace variable names. BaseType must be int8, uint8, int16, uint16, or int32. For example, the following code defines an enumerated type called sysMode that inherits from the built-in type int32: classdef(Enumeration) sysMode < int32 ... end 3 Define enumerated values in an enumeration section: classdef(Enumeration) EnumTypeName < BaseType 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 Each enumerated value consists of a string EnumName and an underlying integer N. Each EnumName must be unique within its type. If the enumerated value name 9-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Enumerated Data for Code Generation does not include the class name prefix, EnumName must be unique across enumerated types. See “Control Names of Enumerated Type Values in Generated Code” on page 9-26. The underlying integers do not have to be consecutive or ordered, or unique within 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. For examples, see “Include Enumerated Data in Control Flow Statements” on page 9-13. Naming Enumerated Types for Code Generation You must use a unique name for each enumerated data type. Do not use the name of: • A toolbox function supported for code generation. • Another data type. • A variable in the MATLAB base workspace. 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 “Functions and Objects Supported for C and C++ Code Generation — Alphabetical List”. 9-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Operations on Enumerated Data for Code Generation To generate efficient standalone code for enumerated data, you are restricted to the following operations. The examples use the following enumerated class definition: classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end end . Assignment Operator, = Example Result xon = LEDcolor.GREEN xoff = LEDcolor.RED xon = GREEN xoff = RED Relational Operators, < > <= >= == ~= Example Result xon == xoff ans = xon <= xoff ans = 0 1 xon > xoff ans = 0 Cast Operation Example Result double(LEDcolor.RED) ans = 9-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Operations on Enumerated Data for Code Generation Example Result 2 z = 2 y = LEDcolor(z) z = 2 y = RED Indexing Operation Example Result m = [1 2] n = LEDcolor(m) p = n(LEDcolor.GREEN) m = 1 2 n = GREEN RED p = GREEN Control Flow Statements: if, switch, while Statement Example Executable Example if if state == sysMode.ON led = LEDcolor.GREEN; else led = LEDcolor.RED; end switch switch button case VCRButton.Stop state = VCRState.Stop; “if Statement with Enumerated Data Types” on page 9-13 “switch Statement with Enumerated Data Types” on page 9-14 9-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Statement Example Executable Example case VCRButton.PlayOrPause state = VCRState.Play; case VCRButton.Next state = VCRState.Forward; case VCRButton.Previous state = VCRState.Rewind; otherwise state = VCRState.Stop; end while while state ~= State.Ready switch state case State.Standby initialize(); state = State.Boot; case State.Boot boot(); state = State.Ready; end end 9-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان “while Statement with Enumerated Data Types” on page 9-16 Include Enumerated Data in Control Flow Statements Include Enumerated Data in Control Flow Statements The following examples define enumerated types that use the base type int32. You can base an enumerated type on one of these built-in integer types: • int8 • uint8 • int16 • uint16 • int32 The base type determines the representation of the enumerated type in the generated C/ C++ code. See “Enumerated Types Supported for Code Generation” on page 9-3. if Statement with Enumerated Data Types This example defines the enumeration types LEDcolor and sysMode. The function displayState uses these enumerated data types to activate an LED display. Class Definition: sysMode classdef(Enumeration) sysMode < int32 enumeration OFF(0), ON(1) end end This definition must reside on the MATLAB path in a file with the same name as the class, sysMode.m. Class Definition: LEDcolor classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end end This definition must reside on the MATLAB path in a file called LEDcolor.m. 9-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data MATLAB Function: displayState This function uses enumerated data to activate an LED display, based on the state of a device. It lights a green LED display to indicate the ON state and lights a red LED display to indicate the OFF state. function led = displayState(state) %#codegen if state == sysMode.ON led = LEDcolor.GREEN; else led = LEDcolor.RED; end Build and Test a MEX Function for displayState 1 Generate a MEX function for displayState. Use the -args option to pass one of the allowable values for the enumerated data input as a sample value. codegen displayState -args {sysMode.ON} 2 Test the function. For example, displayState(sysMode.OFF) ans = RED switch Statement with Enumerated Data Types This example is based on the definition of the enumeration types VCRState and VCRButton. The function VCR uses these enumerated data types to set the state of the VCR. Class Definition: VCRState classdef(Enumeration) VCRState < int32 enumeration Stop(0), Pause(1), Play(2), Forward(3), 9-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Include Enumerated Data in Control Flow Statements Rewind(4) end end This definition must reside on the MATLAB path in a file with the same name as the class, VCRState.m. Class Definition: VCRButton classdef(Enumeration) VCRButton < int32 enumeration Stop(1), PlayOrPause(2), Next(3), Previous(4) end end This definition must reside on the MATLAB path in a file with the same name as the class, VCRButton.m. MATLAB Function: VCR This function uses enumerated data to set the state of a VCR, based on the initial state of the VCR and the state of the VCR button. function s = VCR(button) %#codegen persistent state if isempty(state) state = VCRState.Stop; end switch state case {VCRState.Stop, VCRState.Forward, VCRState.Rewind} state = handleDefault(button); case VCRState.Play switch button case VCRButton.PlayOrPause, state = VCRState.Pause; otherwise, state = handleDefault(button); end case VCRState.Pause 9-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data switch button case VCRButton.PlayOrPause, state = VCRState.Play; otherwise, state = handleDefault(button); end end s = state; function state = handleDefault(button) switch button case VCRButton.Stop, state = VCRState.Stop; case VCRButton.PlayOrPause, state = VCRState.Play; case VCRButton.Next, state = VCRState.Forward; case VCRButton.Previous, state = VCRState.Rewind; otherwise, state = VCRState.Stop; end Build and Test a MEX Function for VCR 1 Generate a MEX function for VCR. Use the -args option to pass one of the allowable values for the enumerated data input as a sample value. codegen -args {VCRButton.Stop} 2 VCR Test the function. For example, s = VCR(VCRButton.Stop) s = Stop while Statement with Enumerated Data Types This example is based on the definition of the enumeration type State. The function Setup uses this enumerated data type to set the state of a device. Class Definition: State classdef(Enumeration) State < int32 enumeration Standby(0), Boot(1), Ready(2) end end 9-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Include Enumerated Data in Control Flow Statements This definition must reside on the MATLAB path in a file with the same name as the class, State.m. MATLAB Function: Setup The following function Setup uses enumerated data to set the state of a device. function s = Setup(initState) %#codegen state = initState; if isempty(state) state = State.Standby; end while state ~= State.Ready switch state case State.Standby initialize(); state = State.Boot; case State.Boot boot(); state = State.Ready; end end s = state; function initialize() % Perform initialization. function boot() % Boot the device. Build and Test a MEX Executable for Setup 1 Generate a MEX executable for Setup. Use the -args option to pass one of the allowable values for the enumerated data input as a sample value. codegen Setup -args {State.Standby} 2 Test the function. For example, s = Setup(State.Standby) s = 9-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Ready 9-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Customize Enumerated Types for Code Generation Customize Enumerated Types for Code Generation Customizing Enumerated Types For code generation, you can customize an enumerated type by using the same techniques that work with MATLAB classes, as described in “Modifying Superclass Methods and Properties”. You can customize an enumerated type by including a methods section in the enumerated class definition. You can override the following methods to customize the behavior of an enumerated type. To override a method, include a customized version of the method in the methods section in the enumerated class definition. If you do not want to override the inherited methods, omit the methods section. Method Description Default Value When to Use Returned or Specified addClassNameToEnumNames Specifies whether the class name becomes a prefix in the generated code. false — prefix is not used. If you want the class name to become a prefix in the generated code, override this method to set the return value to true. See “Control Names of Enumerated Type Values in Generated Code” on page 9-26. Returns the default enumerated value. First value in the enumerated class definition. If you want the default value for the enumerated type to be something other than the first value listed in the enumerated class definition, override this method to specify a default value. See “Specify a Default getDefaultValue 9-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Method Description Default Value When to Use Returned or Specified Enumerated Value” on page 9-20. getHeaderFile Specifies the file in which the enumerated class is defined for code generation. '' If you want to use an enumerated class definition that is specified in a custom header file, override this method to return the path to this header file. In this case, the code generation software does not generate the class definition. See “Specify a Header File” on page 9-21 Specify a Default Enumerated Value If the value of a variable that is cast to an enumerated type does not match one of the enumerated type values: • Generated MEX reports an error. • Generated C/C++ code replaces the value of the variable with the enumerated type default value. Unless you specify otherwise, the default value for an enumerated type is the first value in the enumerated class definition. To specify a different default value, add your own getDefaultValue method to the methods section. The following code shows a shell for the getDefaultValue method: function retVal = getDefaultValue() % GETDEFAULTVALUE Returns the default enumerated value. % This value must be an instance of the enumerated class. % If this method is not defined, the first enumerated value is used. retVal = ThisClass.EnumName; end 9-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Customize Enumerated Types for Code Generation To customize this method, provide a value for ThisClass.EnumName that specifies the default that you want. ThisClass must be the name of the class within which the method exists. EnumName must be the name of an enumerated value defined in that class. For example: classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end methods (Static) function y = getDefaultValue() y = LEDcolor.RED; end end end This example defines the default as LEDcolor.RED. If this method does not appear, the default value is LEDcolor.GREEN, because that value is the first value listed in the enumerated class definition. Specify a Header File To prevent the declaration of an enumerated type from being embedded in the generated code, allowing you to provide the declaration in an external file, include the following method in the enumerated class methods section: function y = getHeaderFile() % GETHEADERFILE File where type is defined for generated code. % If specified, this file is #included where required in the code. % Otherwise, the type is written out in the generated code. y = 'filename'; end Substitute a legal filename for filename. Be sure to provide a filename suffix, typically .h. Providing the method replaces the declaration that appears in the generated code with an #include statement like: #include "imported_enum_type.h" The getHeaderFile method does not create the declaration file itself. You must provide a file of the specified name that declares the enumerated data type. The file can also contain definitions of enumerated types that you do not use in your MATLAB code. For example, to use the definition of LEDcolor in my_LEDcolor.h: 9-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data 1 Modify the definition of LEDcolor to override the getHeaderFile method to return the name of the external header file: classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end methods(Static) function y=getHeaderFile() y='my_LEDcolor.h'; end end end 2 In the current folder, provide a header file, my_LEDcolor.h, that contains the definition: enum LEDcolor { GREEN = 1, RED }; typedef enum LEDcolor LEDcolor; 3 Generate a library for the function displayState that takes one input of enumerated data type sysMode. codegen -config:lib -report displayState -args {sysMode.ON} codegen generates a C static library with the default name, displayState, and supporting files in the default folder, codegen/lib/displayState. 4 Click the View Report link. 5 In the report, on the C Code tab, click the link to the displayState_types.h file. The header file contains a #include statement for the external header file. #include "my_LEDcolor.h" It does not include a declaration for the enumerated class. 9-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use Enumerated Types in LED Control Function Use Enumerated Types in LED Control Function This example shows how to define, use, and generate code for enumerated types in a function that controls an LED. In this example, the enumerated types inherit from base type int32. The base type can be int8, uint8, int16, uint16, or int32. 1 Define the enumerated type sysMode. Store it in sysMode.m on the MATLAB path. classdef(Enumeration) sysMode < int32 enumeration OFF(0), ON(1) end end 2 Define the enumerated type LEDcolor. Store it in LEDcolor.m on the MATLAB path. classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end end 3 Define the function displayState, which uses enumerated data to activate an LED display, based on the state of a device. displayState lights a green LED display to indicate the ON state. It lights a red LED display to indicate the OFF state. Store displayState in displayState.m on the MATLAB path. function led = displayState(state) %#codegen if state == sysMode.ON led = LEDcolor.GREEN; else led = LEDcolor.RED; end 4 Generate the MEX function displayState_mex. Specify that displayState has one input that is an enumerated data type sysMode. codegen -report displayState -args {sysMode.ON} 5 Test the MEX function. 9-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data displayState_mex(sysMode.OFF) ans = RED 6 Generate a static library for the function displayState that takes one input of enumerated data type sysMode. codegen -config:lib -report displayState -args {sysMode.ON} codegen generates a C static library with the default name, displayState. It generates supporting files in the default folder, codegen/lib/displayState. 7 Click the View Report link. 8 In the report, on the C Code tab, click the link to the displayState_types.h file. The report displays the header file containing the enumerated data type definition. enum LEDcolor { GREEN = 1, RED }; typedef enum LEDcolor LEDcolor; The enumerated type LEDcolor is represented as a C enumerated type because the base type in the class definition for LEDcolor is int32. When the base type is int8, uint8, int16, or uint16, the code generation software generates a typedef for the enumerated type. It generates #define statements for the enumerated type values. For example: typedef short LEDcolor; #define GREEN ((LEDcolor)1) #define RED ((LEDcolor)2) Related Examples • “Generate Code for Enumerated Data from MATLAB Algorithms” on page 9-7 • “Customize Enumerated Types for Code Generation” on page 9-19 9-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use Enumerated Types in LED Control Function More About • “Enumerated Data Definition for Code Generation” on page 9-2 • “Enumerated Types Supported for Code Generation” on page 9-3 9-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Control Names of Enumerated Type Values in Generated Code This example shows how to control whether generated enumerated type value names include the class name prefix from the enumerated type definition. By default, the generated enumerated type value name does not include the class name prefix. 1 Define the enumerated type sysMode. Store it in sysMode.m on the MATLAB path. classdef(Enumeration) sysMode < int32 enumeration OFF(0), ON(1) end end 2 Define the enumerated type LEDcolor. Store it in LEDcolor.m on the MATLAB path. classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end end 3 Define the function displayState, which uses enumerated data to activate an LED display, based on the state of a device. displayState lights a green LED display to indicate the ON state and lights a red LED display to indicate the OFF state. Store in displayState.m on the MATLAB path. function led = displayState(state) %#codegen if state == sysMode.ON led = LEDcolor.GREEN; else led = LEDcolor.RED; end 4 Generate a library for the function displayState that takes one input of enumerated data type sysMode. codegen -config:lib -report displayState -args {sysMode.ON} 9-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Control Names of Enumerated Type Values in Generated Code codegen generates a C static library with the default name, displayState, and supporting files in the default folder, codegen/lib/displayState. 5 Click the View Report link. 6 In the report, on the C Code tab, click the link to the displayState_types.h file. The report displays the header file containing the enumerated data type definition. enum LEDcolor { GREEN = 1, RED }; typedef enum LEDcolor LEDcolor; The enumerated value names do not include the class name prefix LEDcolor_. 7 Modify the definition of LEDcolor to add the addClassNameToEnumNames method. Set the return value to true so that the enumerated value names in the generated code contain the class prefix. classdef(Enumeration) LEDcolor < int32 enumeration GREEN(1), RED(2) end methods(Static) function y=addClassNameToEnumNames() y=true; end end end 8 Clear existing class instances. clear classes 9 Generate code. codegen -config:lib -report displayState -args {sysMode.ON} 10 Open the code generation report and look at the enumerated type definition in displayState_types.h. 9-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data enum LEDcolor { LEDcolor_GREEN = 1, LEDcolor_RED }; typedef enum LEDcolor LEDcolor; The enumerated value names include the class name prefix. 9-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Change and Reload Enumerated Data Types Change and Reload Enumerated Data Types You can change the definition of an enumerated data type by editing and saving the file that contains the definition. You do not need to inform MATLAB that a class definition has changed. MATLAB automatically reads the modified definition when you save the file. However, the class definition changes do not take full effect if class instances (enumerated values) exist that reflect the previous class definition. Such instances might exist in the base workspace or might be cached. The following table explains options for removing instances of an enumerated data type from the base workspace and cache. If In Base Workspace... If In Cache... Do one of the following: • Clear MEX functions that are caching instances of the class. • Locate and delete specific obsolete instances. • Delete the classes from the workspace by using the clear classes command. For more information, see clear. 9-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data Restrictions on Use of Enumerated Data in for-Loops Do not use enumerated data as the loop counter variable in for- loops To iterate over a range of enumerated data with consecutive values, in the loop counter, cast the enumerated data to a built-in integer type. The size of the built-in integer type must be big enough to contain the enumerated value. For example, suppose you define an enumerated type ColorCodes as follows: classdef(Enumeration) ColorCodes < int32 enumeration Red(1), Blue(2), Green(3), Yellow(4), Purple(5) end end Because the enumerated values are consecutive, you can use ColorCodes data in a for-loop like this: ... for i = int32(ColorCodes.Red):int32(ColorCodes.Purple) c = ColorCodes(i); ... end 9-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Toolbox Functions That Support Enumerated Types for Code Generation Toolbox Functions That Support Enumerated Types for Code Generation The following MATLAB toolbox functions support enumerated types for code generation: • cast • cat • circshift • flipdim • fliplr • flipud • histc • intersect • ipermute • isequal • isequaln • isfinite • isinf • ismember • isnan • issorted • length • permute • repmat • reshape • rot90 • setdiff • setxor • shiftdim • sort • sortrows 9-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Code Generation for Enumerated Data • squeeze • union • unique 9-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes • “MATLAB Classes Definition for Code Generation” on page 10-2 • “Classes That Support Code Generation” on page 10-7 • “Generate Code for MATLAB Value Classes” on page 10-8 • “Generate Code for MATLAB Handle Classes and System Objects” on page 10-13 • “MATLAB Classes in Code Generation Reports” on page 10-15 • “Troubleshooting Issues with MATLAB Classes” on page 10-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes MATLAB Classes Definition for Code Generation To generate efficient standalone code for MATLAB classes, you must use classes differently than when running your code in the MATLAB environment. What’s Different More Information Class must be in a single file. Because “Creating a Single, Self-Contained Class of this limitation, code generation is not Definition File” supported for a class definition that uses an @-folder. Restricted set of language features. “Language Limitations” on page 10-2 Restricted set of code generation features. “Code Generation Features Not Compatible with Classes” on page 10-3 Definition of class properties. “Defining Class Properties for Code Generation” on page 10-4 Use of handle classes. “Generate Code for MATLAB Handle Classes and System Objects” on page 10-13 Calls to base class constructor. “Calls to Base Class Constructor” on page 10-5 Global variables containing MATLAB objects are not supported for code generation. N/A Inheritance from built-in MATLAB classes “Inheritance from Built-In MATLAB is not supported. Classes Not Supported” on page 10-6 Language Limitations Although code generation support is provided for common features of classes such as properties and methods, there are a number of advanced features which are not supported, such as: • Events • Listeners • Arrays of objects 10-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB Classes Definition for Code Generation • Recursive data structures • Linked lists • Trees • Graphs • Overloadable operators subsref, subsassign, and subsindex In MATLAB, classes can define their own versions of the subsref, subsassign, and subsindex methods. Code generation does not support classes that have their own definitions of these methods. • The empty method In MATLAB, classes have a built-in static method, empty, which creates an empty array of the class. Code generation does not support this method. • The following MATLAB handle class methods: • addlistener • delete • eq • findobj • findpro • The AbortSet property attribute Code Generation Features Not Compatible with Classes • You can generate code for entry-point MATLAB functions that use classes, but you cannot generate code directly for a MATLAB class. For example, if ClassNameA is a class definition, you cannot generate code by executing: codegen ClassNameA • If an entry-point MATLAB function has an input or output that is a MATLAB class, you cannot generate code for this function. For example, if function foo takes one input, a, that is a MATLAB object, you cannot generate code for foo by executing: 10-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes codegen foo -args {a} • Code generation does not support assigning an object of a value class into a nontunable property. For example, obj.prop=v; is invalid when prop is a nontunable property and v is an object based on a value class. • You cannot use coder.extrinsic to declare a class or method as extrinsic. • You cannot pass a MATLAB class to the coder.ceval function. • If you use classes in code in the MATLAB Function block, you cannot use the debugger to view class information. • The coder.nullcopy function does not support MATLAB classes as inputs. Defining Class Properties for Code Generation For code generation, you must define class properties differently than you normally would when running your code in the MATLAB environment: • After defining a property, do not assign it an incompatible type. Do not use a property before attempting to grow it. When you define class properties for code generation, consider the same factors that you take into account when defining variables. In the MATLAB language, variables can change their class, size, or complexity dynamically at run time so you can use the same variable to hold a value of varying class, size, or complexity. C and C++ use static typing. Before using variables, to determine their type, the code generation software requires a complete assignment to each variable. Similarly, before using properties, you must explicitly define their class, size, and complexity. • Initial values: • If the property does not have an explicit initial value, the code generation software assumes that it is undefined at the beginning of the constructor. The code generation software does not assign an empty matrix as the default. • If the property does not have an initial value and the code generation software cannot determine that the property is assigned prior to first use, the software generates a compilation error. • For System objects, if a nontunable property is a structure, you must completely assign the structure. You cannot do partial assignment using subscripting. For example, for a nontunable property, you can use the following assignment: 10-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB Classes Definition for Code Generation mySystemObject.nonTunableProperty=struct('fieldA','a','fieldB','b'); You cannot use the following partial assignments: mySystemObject.nonTunableProperty.fieldA = a; mySystemObject.nonTunableProperty.fieldB = b; • If dynamic memory allocation is enabled, code generation supports variable-size properties for handle classes. Without dynamic memory allocation, you cannot generate code for handle classes that have variable-size properties. • coder.varsize is not supported for class properties. • MATLAB computes class initial values at class loading time before code generation. If you use persistent variables in MATLAB class property initialization, the value of the persistent variable computed when the class loads belongs to MATLAB; it is not the value used at code generation time. If you use coder.target in MATLAB class property initialization, coder.target('MATLAB') returns true (1). Calls to Base Class Constructor If a class constructor contains a call to the constructor of the base class, the call to the base class constructor must come before for, if, return, switch or while statements. For example, if you define a class B based on class A: classdef B < A methods function obj = B(varargin) if nargin == 0 a = 1; b = 2; elseif nargin == 1 a = varargin{1}; b = 1; elseif nargin == 2 a = varargin{1}; b = varargin{2}; end obj = [email protected](a,b); end end end 10-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes Because the class definition for B uses an if statement before calling the base class constructor for A, you cannot generate code for function callB: function [y1,y2] = callB x = B; y1 = x.p1; y2 = x.p2; end However, you can generate code for callB if you define class B as: classdef B < A methods function obj = NewB(varargin) [a,b] = getaandb(varargin{:}); obj = [email protected](a,b); end end end function [a,b] = getaandb(varargin) if nargin == 0 a = 1; b = 2; elseif nargin == 1 a = varargin{1}; b = 1; elseif nargin == 2 a = varargin{1}; b = varargin{2}; end end Inheritance from Built-In MATLAB Classes Not Supported You cannot generate code for classes that inherit from built-in MATLAB classes. For example, you cannot generate code for the following class: classdef myclass < double 10-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Classes That Support Code Generation Classes That Support Code Generation You can generate code for MATLAB value and handle classes and user-defined System objects. Your class can have multiple methods and properties and can inherit from multiple classes. To generate code for: Example: Value classes “Generate Code for MATLAB Value Classes” on page 10-8 Handle classes including user-defined System objects “Generate Code for MATLAB Handle Classes and System Objects” on page 10-13 For more information, see: • “Classes in the MATLAB Language” • “MATLAB Classes Definition for Code Generation” on page 10-2 10-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes Generate Code for MATLAB Value Classes This example shows how to generate code for a MATLAB value class and then view the generated code in the code generation report. 1 In a writable folder, create a MATLAB value class, Shape. Save the code as Shape.m. classdef Shape % SHAPE Create a shape at coordinates % centerX and centerY properties centerX; centerY; end properties (Dependent = true) area; end methods function out = get.area(obj) out = obj.getarea(); end function obj = Shape(centerX,centerY) obj.centerX = centerX; obj.centerY = centerY; end end methods(Abstract = true) getarea(obj); end methods(Static) function d = distanceBetweenShapes(shape1,shape2) xDist = abs(shape1.centerX - shape2.centerX); yDist = abs(shape1.centerY - shape2.centerY); d = sqrt(xDist^2 + yDist^2); end end end 2 In the same folder, create a class, Square, that is a subclass of Shape. Save the code as Square.m. classdef Square < Shape % Create a Square at coordinates center X and center Y 10-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for MATLAB Value Classes % with sides of length of side properties side; end methods function obj = Square(side,centerX,centerY) [email protected](centerX,centerY); obj.side = side; end function Area = getarea(obj) Area = obj.side^2; end end end 3 In the same folder, create a class, Rhombus, that is a subclass of Shape. Save the code as Rhombus.m. classdef Rhombus < Shape properties diag1; diag2; end methods function obj = Rhombus(diag1,diag2,centerX,centerY) [email protected](centerX,centerY); obj.diag1 = diag1; obj.diag2 = diag2; end function Area = getarea(obj) Area = 0.5*obj.diag1*obj.diag2; end end end 4 Write a function that uses this class. use_shape function [TotalArea, Distance] = %#codegen s = Square(2,1,2); r = Rhombus(3,4,7,10); TotalArea = s.area + r.area; Distance = Shape.distanceBetweenShapes(s,r); 5 Generate a static library for use_shape and generate a code generation report. 10-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes codegen -config:lib -report use_shape codegen generates a C static library with the default name, use_shape, and supporting files in the default folder, codegen/lib/use_shape. 6 Click the View report link. 7 In the report, on the MATLAB code tab, click the link to the Rhombus class. The report displays the class definition of the Rhombus class and highlights the class constructor. On the Variables tab, it provides details of the variables used in the class. If a variable is a MATLAB object, by default, the report displays the object without displaying its properties. To view the list of properties, expand the list. Within the list of properties, the list of inherited properties is collapsed. In the following report, the lists of properties and inherited properties are expanded. 8 At the top right side of the report, expand the Calls list. 10-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for MATLAB Value Classes The Calls list shows that there is a call to the Rhombus constructor from use_shape and that this constructor calls the Shape constructor. 9 The constructor for the Rhombus class calls the Shape method of the base Shape class: [email protected] In the report, click the Shape link in this call. 10-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes The link takes you to the Shape method in the Shape class definition. 10-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for MATLAB Handle Classes and System Objects Generate Code for MATLAB Handle Classes and System Objects This example shows how to generate code for a user-defined System object and then view the generated code in the code generation report. 1 In a writable folder, create a System object, AddOne, which subclasses from matlab.System. Save the code as AddOne.m. classdef AddOne < matlab.System % ADDONE Compute an output value that increments the input by one methods (Access=protected) % stepImpl method is called by the step method function y = stepImpl(~,x) y = x+1; end end end 2 Write a function that uses this System object. function y = testAddOne(x) %#codegen p = AddOne(); y = p.step(x); end 3 Generate a MEX function for this code. codegen -report testAddOne -args {0} The -report option instructs codegen to generate a code generation report, even if no errors or warnings occur. The -args option specifies that the testAddOne function takes one scalar double input. >> codegen -report testAddOne -args {0} Code generation successful: View report 4 Click the View report link. 5 In the report, on the MATLAB Code tab Functions panel, click testAddOne, then click the Variables tab. You can view information about the variable p on this tab. 10-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes 6 To view the class definition, on the Classes panel, click AddOne. 10-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB Classes in Code Generation Reports MATLAB Classes in Code Generation Reports What Reports Tell You About Classes Code generation reports: • Provide a hierarchical tree of the classes used in your MATLAB code. • Display a list of methods for each class in the MATLAB code tab. • Display the objects used in your MATLAB code together with their properties on the Variables tab. • Provide a filter so that you can sort methods by class, size, and complexity. • List the set of calls from and to the selected method in the Calls list. How Classes Appear in Code Generation Reports In the MATLAB Code Tab The report displays an alphabetical hierarchical list of the classes used in the your MATLAB code. For each class, you can: • Expand the class information to view the class methods. • View a class method by clicking its name. The report displays the methods in the context of the full class definition. • Filter the methods by size, complexity, and class by using the Filter functions and methods option. Default Constructors If a class has a default constructor, the report displays the constructor in italics. Specializations If the same class is specialized into multiple different classes, the report differentiates the specializations by grouping each one under a single node in the tree. The report associates the class definition functions and static methods with the primary node. It associates the instance-specific methods with the corresponding specialized node. For example, consider a base class, Shape that has two specialized subclasses, Rhombus and Square. The Shape class has an abstract method, getarea, and a static method, distanceBetweenShapes. The code generation report, displays a 10-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes node for the specialized Rhombus and Square classes with their constructors and getarea method. It displays a node for the Shape class and its associated static method, distanceBetweenShapes, and two instances of the Shape class, Shape1 and Shape2. Packages If you define classes as part of a package, the report displays the package in the list of classes. You can expand the package to view the classes that it contains. For more information about packages, see “Packages Create Namespaces”. In the Variables Tab The report displays the objects in the selected function or class. By default, for classes that have properties, the list of properties is collapsed. To expand the list, click the + symbol next to the object name. Within the list of properties, the list of inherited properties is collapsed. To expand the list of inherited properties, click the + symbol next to Inherited. The report displays the properties using just the base property name, not the fully qualified name. For example, if your code uses variable obj1 that is a MATLAB object 10-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB Classes in Code Generation Reports with property prop1, then the report displays the property as prop1 not obj1.prop1. When you sort the Variables column, the sort order is based on the fully qualified property name. In the Call Stack The call stack lists the functions and methods in the order that the top-level function calls them. It also lists the local functions that each function calls. How to Generate a Code Generation Report Add the -report option to your codegen command (requires a MATLAB Coder license) 10-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 Code Generation for MATLAB Classes Troubleshooting Issues with MATLAB Classes Class class does not have a property with name name If a MATLAB class has a method, mymethod, that returns a handle class with a property, myprop, you cannot generate code for the following type of assignment: obj.mymethod().myprop=... For example, consider the following classes: classdef MyClass < handle properties myprop end methods function this = MyClass this.myprop = MyClass2; end function y = mymethod(this) y = this.myprop; end end end classdef MyClass2 < handle properties aa end end You cannot generate code for function foo. function foo h = MyClass; h.mymethod().aa = 12; In this function, h.mymethod() returns a handle object of type MyClass2. In MATLAB, the assignment h.mymethod().aa = 12; changes the property of that object. Code generation does not support this assignment. 10-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Troubleshooting Issues with MATLAB Classes Workaround Rewrite the code to return the object and then assign a value to a property of the object. function foo h = MyClass; b=h.mymethod(); b.aa=12; 10-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-20 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11 Code Generation for Function Handles • “Function Handle Definition for Code Generation” on page 11-2 • “Define and Pass Function Handles for Code Generation” on page 11-3 • “Function Handle Limitations for Code Generation” on page 11-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11 Code Generation for Function Handles Function Handle Definition for Code Generation You can use function handles to invoke functions indirectly and parameterize operations that you repeat frequently. You can perform the following operations with function handles: • Define handles that reference user-defined functions and built-in functions supported for code generation (see “Functions and Objects Supported for C and C++ Code Generation — Alphabetical List”) Note: You cannot define handles that reference extrinsic MATLAB functions. • Define function handles as scalar values • Define structures that contain function handles • Pass function handles as arguments to other functions (excluding extrinsic functions) To generate efficient standalone code for enumerated data, you are restricted to using a subset of the operations you can perform with function handles in MATLAB, as described in “Function Handle Limitations for Code Generation” on page 11-5 11-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define and Pass Function Handles for Code Generation Define and Pass Function Handles for Code Generation The following code example shows how to define and call function handles for code generation. You can copy the example to a MATLAB Function block in Simulink or MATLAB function in Stateflow. To convert this function to a MEX function using codegen, uncomment the two calls to the assert function, highlighted below: function addval(m) %#codegen % % % % Define class and size of primary input m Uncomment next two lines to build MEX function with codegen assert(isa(m,'double')); assert(all (size(m) == [3 3])); % Pass function handle to addone % to add one to each element of m m = map(@addone, m); disp(m); % Pass function handle to addtwo % to add two to each element of m m = map(@addtwo, m); disp(m); function y = map(f,m) y = m; for i = 1:numel(y) y(i) = f(y(i)); end function y = addone(u) y = u + 1; function y = addtwo(u) y = u + 2; This code passes function handles @addone and @addtwo to the function map which increments each element of the matrix m by the amount prescribed by the referenced function. Note that map stores the function handle in the input variable f and then uses f to invoke the function — in this case addone first and then addtwo. 11-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11 Code Generation for Function Handles If you have MATLAB Coder, you can use the function codegen to convert the function addval to a MEX executable that you can run in MATLAB. Follow these steps: 1 At the MATLAB command prompt, issue this command: codegen addval 2 Define and initialize a 3-by-3 matrix by typing a command like this at the MATLAB prompt: m = zeros(3) 3 Execute the function by typing this command: addval(m) You should see the following result: 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 For more information, see “MEX Function Generation at the Command Line”. 11-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Function Handle Limitations for Code Generation Function Handle Limitations for Code Generation You cannot use the same bound variable to reference different function handles. After you bind a variable to a specific function, you cannot use the same variable to reference two different function handles, as in this example: %Incorrect code ... x = @plus; x = @minus; ... This code produces a compilation error. You cannot pass function handles to or from coder.ceval. You cannot pass function handles as inputs to or outputs from coder.ceval. For example, suppose that f and str.f are function handles: f = @sin; str.x = pi; str.f = f; The following statements result in compilation errors: coder.ceval('foo', @sin); coder.ceval('foo', f); coder.ceval('foo', str); You cannot pass function handles to or from extrinsic functions. You cannot pass function handles to or from feval and other extrinsic MATLAB functions. For more information, see “Declaring MATLAB Functions as Extrinsic Functions” on page 13-12. 11-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11 Code Generation for Function Handles You cannot pass function handles to or from primary functions. You cannot pass function handles as inputs to or outputs from primary functions. For example, consider this function: function x = plotFcn(fhandle, data) assert(isa(fhandle,'function_handle') && isa(data,'double')); plot(data, fhandle(data)); x = fhandle(data); In this example, the function plotFcn receives a function handle and its data as primary inputs. plotFcn attempts to call the function referenced by the fhandle with the input data and plot the results. However, this code generates a compilation error. The error indicates that the function isa does not recognize 'function_handle' as a class name when called inside a MATLAB function to specify properties of primary inputs. 11-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 Defining Functions for Code Generation • “Specify Variable Numbers of Arguments” on page 12-2 • “Supported Index Expressions” on page 12-3 • “Apply Operations to a Variable Number of Arguments” on page 12-4 • “Implement Wrapper Functions” on page 12-6 • “Pass Property/Value Pairs” on page 12-7 • “Variable Length Argument Lists for Code Generation” on page 12-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 Defining Functions for Code Generation Specify Variable Numbers of Arguments You can use varargin in a function definition to specify that the function accepts a variable number of input arguments for a given input argument. You can use varargout in a function definition to specify that the function returns a variable number of arguments for a given output argument. When you use varargin and varargout for code generation, there are the following limitations: • You cannot use varargout in the function definition for a top-level function. • You cannot use varargin in the function definition for a top-level function in a MATLAB Function block in a Simulink model, or in a MATLAB function in a Stateflow diagram. • If you use varargin to define an argument to a top-level function, the code generation software generates the function with a fixed number of arguments. This fixed number of arguments is based on the number of example arguments that you provide on the command line or in a MATLAB Coder project test file. Common applications of varargin and varargout for code generation are to: • “Apply Operations to a Variable Number of Arguments” on page 12-4 • “Implement Wrapper Functions” on page 12-6 • “Pass Property/Value Pairs” on page 12-7 Code generation relies on loop unrolling to produce simple and efficient code for varargin and varargout. This technique permits most common uses of varargin and varargout, but some uses are not allowed (see “Variable Length Argument Lists for Code Generation” on page 12-9). For more information about using varargin and varargout in MATLAB functions, see “Passing Variable Numbers of Arguments”. 12-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Supported Index Expressions Supported Index Expressions In MATLAB, varargin and varargout are cell arrays. Generated code does not support cell arrays, but does allow you to use the most common syntax — curly braces {} — for indexing into varargin and varargout arrays, as in this example: %#codegen function [x,y,z] = fcn(a,b,c) [x,y,z] = subfcn(a,b,c); function varargout = subfcn(varargin) for i = 1:length(varargin) varargout{i} = varargin{i}; end You can use the following index expressions. The exp arguments must be constant expressions or depend on a loop index variable. Expression varargin (read only) varargout (read and write) Description varargin{exp} Read the value of element exp varargin{exp1: exp2} Read the values of elements exp1 through exp2 varargin{:} Read the values of all elements varargout{exp} Read or write the value of element exp Note: The use of () is not supported for indexing into varargin and varargout arrays. 12-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 Defining Functions for Code Generation Apply Operations to a Variable Number of Arguments You can use varargin and varargout in for-loops to apply operations to a variable number of arguments. To index into varargin and varargout arrays in generated code, the value of the loop index variable must be known at compile time. Therefore, during code generation, the compiler attempts to automatically unroll these for-loops. Unrolling eliminates the loop logic by creating a separate copy of the loop body in the generated code for each iteration. Within each iteration, the loop index variable becomes a constant. For example, the following function automatically unrolls its for-loop in the generated code: %#codegen function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt) [cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt); function varargout = inch_2_cm(varargin) for i = 1:length(varargin) varargout{i} = varargin{i} * 2.54; end When to Force Loop Unrolling To automatically unroll for-loops containing varargin and varargout expressions, the relationship between the loop index expression and the index variable must be determined at compile time. In the following example, the function fcn cannot detect a logical relationship between the index expression j and the index variable i: %#codegen function [x,y,z] = fcn(a,b,c) [x,y,z] = subfcn(a,b,c); function varargout = subfcn(varargin) j = 0; for i = 1:length(varargin) j = j+1; varargout{j} = varargin{j}; end As a result, the function does not unroll the loop and generates a compilation error: 12-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Apply Operations to a Variable Number of Arguments Nonconstant expression or empty matrix. This expression must be constant because its value determines the size or class of some expression. To fix the problem, you can force loop unrolling by wrapping the loop header in the function coder.unroll, as follows: %#codegen function [x,y,z] = fcn(a,b,c) [x,y,z] = subfcn(a,b,c); function varargout = subfcn(varargin) j = 0; for i = coder.unroll(1:length(varargin)) j = j + 1; varargout{j} = varargin{j}; end; Using Variable Numbers of Arguments in a for-Loop The following example multiplies a variable number of input dimensions in inches by 2.54 to convert them to centimeters: %#codegen function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt) [cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt); function varargout = inch_2_cm(varargin) for i = 1:length(varargin) varargout{i} = varargin{i} * 2.54; end Key Points About the Example • varargin and varargout appear in the local function inch_2_cm, not in the toplevel function conv_2_metric. • The index into varargin and varargout is a for-loop variable For more information, see “Variable Length Argument Lists for Code Generation” on page 12-9. 12-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 Defining Functions for Code Generation Implement Wrapper Functions You can use varargin and varargout to write wrapper functions that accept up to 64 inputs and pass them directly to another function. Passing Variable Numbers of Arguments from One Function to Another The following example passes a variable number of inputs to different optimization functions, based on a specified input method: %#codegen function answer = fcn(method,a,b,c) answer = optimize(method,a,b,c); function answer = optimize(method,varargin) if strcmp(method,'simple') answer = simple_optimization(varargin{:}); else answer = complex_optimization(varargin{:}); end ... Key Points About the Example • You can use {:} to read all elements of varargin and pass them to another function. • You can mix variable and fixed numbers of arguments. For more information, see “Variable Length Argument Lists for Code Generation” on page 12-9. 12-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Pass Property/Value Pairs Pass Property/Value Pairs You can use varargin to pass property/value pairs in functions. However, for code generation, you must take precautions to avoid type mismatch errors when evaluating varargin array elements in a for-loop: If Do This: You assign varargin array elements to local variables in the for-loop Verify that for all pairs, the size, type, and complexity are the same for each property and the same for each value Properties or values have different sizes, types, or complexity Do not assign varargin array elements to local variables in a for-loop; reference the elements directly For example, in the following function test1, the sizes of the property strings and numeric values are not the same in each pair: %#codegen function test1 v = create_value('size', 18, 'rgb', [240 9 44]); end function v = create_value(varargin) v = new_value(); for i = 1 : 2 : length(varargin) name = varargin{i}; value = varargin{i+1}; switch name case 'size' v = set_size(v, value); case 'rgb' v = set_color(v, value); otherwise end end end ... Generated code determines the size, type, and complexity of a local variable based on its first assignment. In this example, the first assignments occur in the first iteration of the for-loop: 12-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 Defining Functions for Code Generation • Defines local variable name with size equal to 4 • Defines local variable value with a size of scalar However, in the second iteration, the size of the property string changes to 3 and the size of the numeric value changes to a vector, resulting in a type mismatch error. To avoid such errors, reference varargin array values directly, not through local variables, as highlighted in this code: %#codegen function test1 v = create_value('size', 18, 'rgb', [240 9 44]); end function v = create_value(varargin) v = new_value(); for i = 1 : 2 : length(varargin) switch varargin{i} case 'size' v = set_size(v, varargin{i+1}); case 'rgb' v = set_color(v, varargin{i+1}); otherwise end end end ... 12-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Variable Length Argument Lists for Code Generation Variable Length Argument Lists for Code Generation Use variable length argument lists in top-level functions according to guidelines When you use varargin and varargout for code generation, there are the following limitations: • You cannot use varargout in the function definition for a top-level function. • You cannot use varargin in the function definition for a top-level function in a MATLAB Function block in a Simulink model, or in a MATLAB function in a Stateflow diagram. • If you use varargin to define an argument to a top-level function, the code generation software generates the function with a fixed number of arguments. This fixed number of arguments is based on the number of example arguments that you provide on the command line or in a MATLAB Coder project test file. A top-level function is: • The function called by Simulink in a MATLAB Function block or by Stateflow in a MATLAB function. • The function that you provide on the command line to codegen or fiaccel. For example, the following code generates compilation errors: %#codegen function varargout = inch_2_cm(varargin) for i = 1:length(varargin) varargout{i} = varargin{i} * 2.54; end To fix the problem, write a top-level function that specifies a fixed number of inputs and outputs. Then call inch_2_cm as an external function or local function, as in this example: %#codegen function [cmL, cmW, cmH] = conv_2_metric(inL, inW, inH) [cmL, cmW, cmH] = inch_2_cm(inL, inW, inH); 12-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 Defining Functions for Code Generation function varargout = inch_2_cm(varargin) for i = 1:length(varargin) varargout{i} = varargin{i} * 2.54; end Use curly braces {} to index into the argument list For code generation, you can use curly braces {}, but not parentheses (), to index into varargin and varargout arrays. For more information, see “Supported Index Expressions” on page 12-3. Verify that indices can be computed at compile time If you use an expression to index into varargin or varargout, make sure that the value of the expression can be computed at compile time. For examples, see “Apply Operations to a Variable Number of Arguments” on page 12-4. Do not write to varargin Generated code treats varargin as a read-only variable. If you want to write to input arguments, copy the values into a local variable. 12-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation • “Resolution of Function Calls for Code Generation” on page 13-2 • “Resolution of File Types on Code Generation Path” on page 13-6 • “Compilation Directive %#codegen” on page 13-8 • “Call Local Functions” on page 13-9 • “Call Supported Toolbox Functions” on page 13-10 • “Call MATLAB Functions” on page 13-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation Resolution of Function Calls for Code Generation From a MATLAB function, you can call local functions, supported toolbox functions, and other MATLAB functions. MATLAB resolves function names for code generation as follows: 13-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Resolution of Function Calls for Code Generation Start Dispatch to MATLAB for execution at runtime Yes Function on MATLAB path? No Yes Extrinsic function? No Yes Subfunction? No Function on the code generation path? Yes No Suitable for code generation? Yes No Generate C code Function on MATLAB path? Yes No Generate error 13-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation Key Points About Resolving Function Calls The diagram illustrates key points about how MATLAB resolves function calls for code generation: • Searches two paths, the code generation path and the MATLAB path See “Compile Path Search Order” on page 13-4. • Attempts to compile functions unless the code generation software determines that it should not compile them or you explicitly declare them to be extrinsic. If a MATLAB function is not supported for code generation, you can declare it to be extrinsic by using the construct coder.extrinsic, as described in “Declaring MATLAB Functions as Extrinsic Functions”. During simulation, the code generation software generates code for the call to an extrinsic function, but does not generate the function's internal code. Therefore, simulation can run only on platforms where MATLAB software is installed. During standalone code generation, MATLAB attempts to determine whether the extrinsic function affects the output of the function in which it is called — for example by returning mxArrays to an output variable. Provided that the output does not change, MATLAB proceeds with code generation, but excludes the extrinsic function from the generated code. Otherwise, compilation errors occur. The code generation software detects calls to many common visualization functions, such as plot, disp, and figure. The software treats these functions like extrinsic functions but you do not have to declare them extrinsic using the coder.extrinsic function. • Resolves file type based on precedence rules described in “Resolution of File Types on Code Generation Path” on page 13-6 Compile Path Search Order During code generation, function calls are resolved on two paths: 1 Code generation path MATLAB searches this path first during code generation. The code generation path contains the toolbox functions supported for code generation. 2 MATLAB path 13-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Resolution of Function Calls for Code Generation If the function is not on the code generation path, MATLAB searches this path. MATLAB applies the same dispatcher rules when searching each path (see “Function Precedence Order”). When to Use the Code Generation Path Use the code generation path to override a MATLAB function with a customized version. A file on the code generation path shadows a file of the same name on the MATLAB path. 13-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation Resolution of File Types on Code Generation Path MATLAB uses the following precedence rules for code generation: 13-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Resolution of File Types on Code Generation Path Start M-file and MEX-file in same directory? Yes No Yes MEX-file? No Yes Generate error MDL-file? Compile M-file No Yes P-file? No No Yes M-file? www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13-7 13 Calling Functions for Code Generation Compilation Directive %#codegen Add the %#codegen directive (or pragma) to your function after the function signature to indicate that you intend to generate code for the MATLAB algorithm. Adding this directive instructs the MATLAB code analyzer to help you diagnose and fix violations that would result in errors during code generation. function y = my_fcn(x) %#codegen .... 13-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Call Local Functions Call Local Functions Local functions are functions defined in the body of MATLAB function. They work the same way for code generation as they do when executing your algorithm in the MATLAB environment. The following example illustrates how to define and call a local function mean: function [mean, stdev] = stats(vals) %#codegen % Calculates a statistical mean and a standard % deviation for the values in vals. len = length(vals); mean = avg(vals, len); stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len); plot(vals,'-+'); function mean = avg(array,size) mean = sum(array)/size; 13-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation Call Supported Toolbox Functions You can call toolbox functions directly if they are supported for code generation. For a list of supported functions, see “Functions and Objects Supported for C and C++ Code Generation — Alphabetical List” on page 4-2. 13-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Call MATLAB Functions Call MATLAB Functions The code generation software attempts to generate code for functions, even if they are not supported for C code generation. The software detects calls to many common visualization functions, such as plot, disp, and figure. The software treats these functions like extrinsic functions but you do not have to declare them extrinsic using coder.extrinsic. During simulation, the code generation software generates code for these functions, but does not generate their internal code. During standalone code generation, MATLAB attempts to determine whether the visualization function affects the output of the function in which it is called. Provided that the output does not change, MATLAB proceeds with code generation, but excludes the visualization function from the generated code. Otherwise, compilation errors occur. For example, you might want to call plot to visualize your results in the MATLAB environment. If you generate a MEX function from a function that calls plot and then run the generated MEX function, the code generation software dispatches calls to the plot function to MATLAB. If you generate a library or executable, the generated code does not contain calls to the plot function. The code generation report highlights calls from your MATLAB code to extrinsic functions so that it is easy to determine which functions are supported only in the MATLAB environment. For unsupported functions other than common visualization functions, you must declare the functions (like pause) to be extrinsic (see “Resolution of Function Calls for Code Generation” on page 13-2). Extrinsic functions are not compiled, but instead executed in MATLAB during simulation (see “How MATLAB Resolves Extrinsic Functions During Simulation” on page 13-16). There are two ways to declare a function to be extrinsic: 13-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation • Use the coder.extrinsic construct in main functions or local functions (see “Declaring MATLAB Functions as Extrinsic Functions” on page 13-12). • Call the function indirectly using feval (see “Calling MATLAB Functions Using feval” on page 13-16). Declaring MATLAB Functions as Extrinsic Functions To declare a MATLAB function to be extrinsic, add the coder.extrinsic construct at the top of the main function or a local function: coder.extrinsic('function_name_1', ... , 'function_name_n'); Declaring Extrinsic Functions The following code declares the MATLAB patch function extrinsic in the local function create_plot: function c = pythagoras(a,b,color) %#codegen % Calculates the hypotenuse of a right triangle % and displays the triangle. c = sqrt(a^2 + b^2); create_plot(a, b, color); function create_plot(a, b, color) %Declare patch and axis as extrinsic coder.extrinsic('patch'); x = [0;a;a]; y = [0;0;b]; patch(x, y, color); axis('equal'); The code generation software detects that axis is not supported for code generation and automatically treats it as an extrinsic function. The compiler does not generate code for patch and axis, but instead dispatches them to MATLAB for execution. To test the function, follow these steps: 1 Convert pythagoras to a MEX function by executing this command at the MATLAB prompt: 13-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Call MATLAB Functions codegen -report pythagoras -args {1, 1, [.3 .3 .3]} 2 Click the link to the code generation report and then, in the report, view the MATLAB code for create_plot. The report highlights the patch and axis functions to indicate that they are supported only within the MATLAB environment. 3 Run the MEX function by executing this command: pythagoras_mex(3, 4, [1.0 0.0 0.0]); MATLAB displays a plot of the right triangle as a red patch object: 13-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation When to Use the coder.extrinsic Construct Use the coder.extrinsic construct to: • Call MATLAB functions that do not produce output — such as pause — during simulation, without generating unnecessary code (see “How MATLAB Resolves Extrinsic Functions During Simulation” on page 13-16). • Make your code self-documenting and easier to debug. You can scan the source code for coder.extrinsic statements to isolate calls to MATLAB functions, which can potentially create and propagate mxArrays (see “Working with mxArrays” on page 13-17). 13-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Call MATLAB Functions • Save typing. With one coder.extrinsic statement, each subsequent function call is extrinsic, as long as the call and the statement are in the same scope (see “Scope of Extrinsic Function Declarations” on page 13-15). • Declare the MATLAB function(s) extrinsic throughout the calling function scope (see “Scope of Extrinsic Function Declarations” on page 13-15). To narrow the scope, use feval (see “Calling MATLAB Functions Using feval” on page 13-16). Rules for Extrinsic Function Declarations Observe the following rules when declaring functions extrinsic for code generation: • Declare the function extrinsic before you call it. • Do not use the extrinsic declaration in conditional statements. Scope of Extrinsic Function Declarations The coder.extrinsic construct has function scope. For example, consider the following code: function y = foo %#codegen coder.extrinsic('rat','min'); [N D] = rat(pi); y = 0; y = min(N, D); In this example, rat and min as treated as extrinsic every time they are called in the main function foo. There are two ways to narrow the scope of an extrinsic declaration inside the main function: • Declare the MATLAB function extrinsic in a local function, as in this example: function y = foo %#codegen coder.extrinsic('rat'); [N D] = rat(pi); y = 0; y = mymin(N, D); function y = mymin(a,b) coder.extrinsic('min'); y = min(a,b); Here, the function rat is extrinsic every time it is called inside the main function foo, but the function min is extrinsic only when called inside the local function mymin. 13-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation • Call the MATLAB function using feval, as described in “Calling MATLAB Functions Using feval” on page 13-16. Calling MATLAB Functions Using feval The function feval is automatically interpreted as an extrinsic function during code generation. Therefore, you can use feval to conveniently call functions that you want to execute in the MATLAB environment, rather than compiled to generated code. Consider the following example: function y = foo coder.extrinsic('rat'); [N D] = rat(pi); y = 0; y = feval('min', N, D); Because feval is extrinsic, the statement feval('min', N, D) is evaluated by MATLAB — not compiled — which has the same result as declaring the function min extrinsic for just this one call. By contrast, the function rat is extrinsic throughout the function foo. How MATLAB Resolves Extrinsic Functions During Simulation MATLAB resolves calls to extrinsic functions — functions that do not support code generation — as follows: 13-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Call MATLAB Functions During simulation, MATLAB generates code for the call to an extrinsic function, but does not generate the function's internal code. Therefore, you can run the simulation only on platforms where you install MATLAB software. During code generation, MATLAB attempts to determine whether the extrinsic function affects the output of the function in which it is called — for example by returning mxArrays to an output variable (see “Working with mxArrays” on page 13-17). Provided that the output does not change, MATLAB proceeds with code generation, but excludes the extrinsic function from the generated code. Otherwise, MATLAB issues a compiler error. Working with mxArrays The output of an extrinsic function is an mxArray — also called a MATLAB array. The only valid operations for mxArrays are: • Storing mxArrays in variables 13-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Calling Functions for Code Generation • Passing mxArrays to functions and returning them from functions • Converting mxArrays to known types at run time To use mxArrays returned by extrinsic functions in other operations, you must first convert them to known types, as described in “Converting mxArrays to Known Types” on page 13-18. Converting mxArrays to Known Types To convert an mxArray to a known type, assign the mxArray to a variable whose type is defined. At run time, the mxArray is converted to the type of the variable assigned to it. However, if the data in the mxArray is not consistent with the type of the variable, you get a run-time error. For example, consider this code: function y = foo %#codegen coder.extrinsic('rat'); [N D] = rat(pi); y = min(N, D); Here, the top-level function foo calls the extrinsic MATLAB function rat, which returns two mxArrays representing the numerator N and denominator D of the rational fraction approximation of pi. Although you can pass these mxArrays to another MATLAB function — in this case, min — you cannot assign the mxArray returned by min to the output y. If you run this function foo in a MATLAB Function block in a Simulink model, the code generates the following error during simulation: Function output 'y' cannot be of MATLAB type. To fix this problem, define y to be the type and size of the value that you expect min to return — in this case, a scalar double — as follows: function y = foo %#codegen coder.extrinsic('rat'); [N D] = rat(pi); y = 0; % Define y as a scalar of type double y = min(N,D); 13-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Call MATLAB Functions Restrictions on Extrinsic Functions for Code Generation The full MATLAB run-time environment is not supported during code generation. Therefore, the following restrictions apply when calling MATLAB functions extrinsically: • MATLAB functions that inspect the caller, or read or write to the caller's workspace do not work during code generation. Such functions include: • dbstack • evalin • assignin • save • The MATLAB debugger cannot inspect variables defined in extrinsic functions. • Functions in generated code may produce unpredictable results if your extrinsic function performs the following actions at run time: • Change folders • Change the MATLAB path • Delete or add MATLAB files • Change warning states • Change MATLAB preferences • Change Simulink parameters Limit on Function Arguments You can call functions with up to 64 inputs and 64 outputs. 13-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13-20 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion • “Convert MATLAB Code to Fixed-Point C Code” on page 14-3 • “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 14-4 • “Propose Fixed-Point Data Types Based on Derived Ranges” on page 14-18 • “Type Proposal Settings” on page 14-34 • “Detect Overflows” on page 14-38 • “Replace the exp Function with a Lookup Table” on page 14-45 • “Replace a Custom Function with a Lookup Table” on page 14-51 • “Enable Plotting Using the Simulation Data Inspector” on page 14-58 • “Log Data for Histogram” on page 14-59 • “View and Modify Variable Information” on page 14-62 • “Build Instrumented MEX Function” on page 14-66 • “Propose Fixed-Point Data Types” on page 14-67 • “Apply Fixed-Point Data Types” on page 14-77 • “Modify Data Type Proposal Settings” on page 14-82 • “Modify Instrumentation Report Settings” on page 14-85 • “Automated Fixed-Point Conversion” on page 14-86 • “Instrumented MEX Functions” on page 14-105 • “Convert Fixed-Point Conversion Project to MATLAB Scripts” on page 14-107 • “Generated Fixed-Point Code” on page 14-110 • “Fixed-Point Code for MATLAB Classes” on page 14-116 • “Automated Fixed-Point Conversion Best Practices” on page 14-119 • “Replacing Functions Using Lookup Table Approximations” on page 14-128 • “MATLAB Language Features Supported for Automated Fixed-Point Conversion” on page 14-129 • “Inspecting Data Using the Simulation Data Inspector” on page 14-131 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion • “Custom Plot Functions” on page 14-134 • “Data Type Issues in Generated Code” on page 14-136 14-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert MATLAB Code to Fixed-Point C Code Convert MATLAB Code to Fixed-Point C Code 1 Create a MATLAB Coder project, add the entry-point function from which you want to generate code, and then define entry-point input types. 2 On the project Overview tab Fixed-Point Conversion pane, select Convert to fixed-point at build time. Then on the project Fixed-Point Conversion pane, click Define and validate fixed-point types to open the Fixed-Point Conversion tool. 3 Compute ranges by either simulating using a test file, using static analysis to derive ranges from design ranges, or both. 4 Validate the proposed data types. See “Validating Types” on page 14-103. 5 Test numerics. See “Testing Numerics” on page 14-103. 6 In the MATLAB Coder project, select the Build tab, set the Output type to build a static or dynamic library, or executable, and then click Build. MATLAB Coder generates fixed-point C code for your entry-point MATLAB function. For more information, see “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 14-4 and “Propose Fixed-Point Data Types Based on Derived Ranges” on page 14-18. 14-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Propose Fixed-Point Data Types Based on Simulation Ranges This example shows how to propose fixed-point data types based on simulation range data. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a New Folder and Copy Relevant Files 1 Create a local working folder, for example, c:\coder\fun_with_matlab. 2 Change to the docroot\toolbox\coder\examples folder. At the MATLAB command line, enter: cd(fullfile(docroot, 'toolbox', 'coder', 'examples')) 3 Copy the fun_with_matlab.m and fun_with_matlab_test.m files to your local working folder. Type Name Description Function code fun_with_matlab.m Entry-point MATLAB function Test file fun_with_matlab_test.m MATLAB script that tests fun_with_matlab.m The fun_with_matlab Function function y = fun_with_matlab(x) %#codegen persistent z 14-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script if isempty(z) z = zeros(2,1); end % [b,a] = butter(2, 0.25) b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175]; a = [1, -0.942809041582063, 0.3333333333333333]; y = zeros(size(x)); for i = 1:length(x) y(i) = b(1)*x(i) + z(1); z(1) = b(2)*x(i) + z(2) - a(2) * y(i); z(2) = b(3)*x(i) - a(3) * y(i); end end The fun_with_matlab_test Script The test script runs the fun_with_matlab function with three input signals: chirp, step, and impulse to cover the full intended operating range of the system. The script then plots the outputs. % fun_with_matlab_test % % Define representative inputs N = 256; % Number of points t = linspace(0,1,N); % Time vector from 0 to 1 second f1 = N/2; % Target frequency of chirp set to Nyquist x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second x_step = ones(1,N); % Step x_impulse = zeros(1,N); % Impulse x_impulse(1) = 1; % Run the function under test x = [x_chirp;x_step;x_impulse]; y = zeros(size(x)); for i = 1:size(x,1) y(i,:) = fun_with_matlab(x(i,:)); end % Plot the results titles = {'Chirp','Step','Impulse'} clf 14-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion for i = 1:size(x,1) subplot(size(x,1),1,i) plot(t,x(i,:),t,y(i,:)) title(titles{i}) legend('Input','Output') end xlabel('Time (s)') figure(gcf) disp('Test complete.') Check Code Generation Readiness In the current working folder, right-click the fun_with_matlab.m function. From the context menu, select Check Code Generation Readiness. The code generation readiness tool screens the code for features and functions that are not supported for code generation. The tool reports that the fun_with_matlab.m function is already suitable for code generation. If your entry-point function is not suitable for code generation, the tool provides a report that lists the source files that contain unsupported features and functions. The report also provides an indication of how much work you must do to make the MATLAB code ready for code generation. Before proposing data types, you must fix these issues. For more information, see “MATLAB Code Analysis”. Create and set up a MATLAB Coder Project 1 Navigate to the work folder that contains the file for this example. 14-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script 2 On the MATLAB Apps tab, select MATLAB Coder and then, in the MATLAB Coder Project dialog box, set Name to fun_with_matlab_project.prj. Alternatively, at the MATLAB command line, enter coder -new fun_with_matlab_project.prj By default, the project opens in the MATLAB workspace. 3 On the project Overview tab, click the Add files link. Browse to the file fun_with_matlab.m and then click OK to add the file to the project. 14-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Define Input Types 1 On the project Overview tab, click the Autodefine types link. 2 In the Autodefine Input Types dialog box, add fun_with_matlab_test as a test file and then click Run. The test file runs and displays the outputs of the filter for each of the input signals. 14-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script MATLAB Coder determines the input types from the test file and then displays them. 3 In the Autodefine Input Types dialog box, click Use These Types. MATLAB Coder sets the type of x to double(1x256). Fixed-Point Conversion 1 On the project Overview tab Fixed-Point Conversion pane, select Convert to fixed-point at build time. 14-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion The project indicates that you must first define the fixed-point data types. 14-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script 2 In the Fixed-Point Conversion pane, click Define and validate fixed-point types. The Fixed-Point Conversion window opens and the tool generates an instrumented MEX function for your entry-point MATLAB function. After generating the MEX function, the tool displays compiled information — type, size, and complexity — for variables in your code. For more information, see “View and Modify Variable Information”. 14-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion If the MEX function generation fails, the tool provides error message links to help you navigate to the code that caused the build issues. If your code contains functions that are not supported for fixed-point conversion, the tool displays these on the Function Replacements tab. For more information, see “Running a Simulation”. 3 Click Run Simulation and verify that the fun_with_matlab_test file is selected as a test file to run. You can add test files and select to run more than one test file during the simulation. If you run multiple test files, the conversion tool merges the simulation results. To clear results, right-click the Variables tab and select Reset entire table. 4 Click Run Simulation and select Log data for histogram. 14-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script By default, the Show code coverage option is selected. This option provides code coverage information that helps you verify that your test file is testing your algorithm over the intended operating range. 5 Click the Run Simulation button. The simulation runs and the conversion tool displays a color-coded code coverage bar to the left of the MATLAB code. Review this information to verify that the test file is testing the algorithm adequately. Here, the dark green line to the left of the code indicates that the code is run every time the algorithm is executed. The orange bar indicates that the code next to it is executed only once. In this example, this is the expected behavior because the code is initializing a persistent variable. If your test file is not covering all your code, update the test or add more test files. 14-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion If a value has ... next to it, the value is rounded. Place your cursor over the ... to view the actual value. The tool displays simulation minimum and maximum ranges on the Variables tab. Using the simulation range data, the software proposes fixed-point types for each variable based on the default type proposal settings, and displays them in the Proposed Type column. The Validate Types option is now enabled. Note: If you manually enter static ranges, these manually-entered ranges take precedence over simulation ranges and the tool uses them to propose data types. In addition, you can also modify and lock the proposed type. 14-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script 6 Examine the proposed types and verify that they cover the full simulation range. To view logged histogram data for a variable, click its Proposed Type field. 14-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion To modify the proposed data types, either enter the required type into the ProposedType field or use the histogram controls. For more information about the histogram, see “Histogram”. 7 To validate the build using the proposed types, click Validate Types. The software validates the proposed types, displays a Validation succeeded message, and enables the Test Numerics option. The project indicates that you have validated the fixed-point data types. If the errors or warnings occur during validation, they are displayed on the Type Validation Output tab. For more information, see “Validating Types”. 8 Click Test Numerics, select Log inputs and outputs for comparison plots, and then click the Test Numerics button. 14-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script The tool runs the test file that you used to define input types to test the fixedpoint MATLAB code. Optionally, you can add test files and select to run more than one test file to test numerics. The software runs both a floating-point and a fixedpoint simulation and then calculates the errors for the output variable y. Because you selected to log inputs and outputs for comparison plots, the tool generates an additional plot for each scalar output. The maximum error is less than 0.03%. For the purpose of this example, this margin of error is acceptable, so you are ready to generate fixed-point C code. If the difference is not acceptable, modify the fixed-point data types or your original algorithm. For more information, see “Testing Numerics”. 9 Return to the MATLAB Coder project. Generate Fixed-Point C Code 1 In the MATLAB Coder project, verify that the Fixed-Point Conversion pane displays Ready for conversion, and then select the Build tab. 2 On this tab, set the Output type to C/C++ Static library. The default output file name is fun_with_matlab. 3 Click Build to generate a library using the default project settings. MATLAB Coder builds the project and generates a C static library and supporting files in the default subfolder, codegen/lib/fun_with_matlab_fixpt. 4 To view the generated code, click View report. 14-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Propose Fixed-Point Data Types Based on Derived Ranges This example shows how to propose fixed-point data types based on static ranges that you specify. The advantage of proposing data types based on derived ranges is that you do not have to provide test files that exercise your algorithm over its full operating range. Running such test files often takes a very long time so you can save time by deriving ranges instead. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a New Folder and Copy Relevant Files 1 Create a local working folder, for example, c:\coder\dti. 2 Change to the docroot\toolbox\coder\examples folder. At the MATLAB command line, enter: cd(fullfile(docroot, 'toolbox', 'coder', 'examples')) 3 Copy the dti.m and dti_test.m files to your local working folder. Type Name Description Function code dti.m Entry-point MATLAB function Test file dti_test.m MATLAB script that tests dti.m 14-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti Function The dti Function The dti function implements a Discrete Time Integrator in MATLAB. function [y, clip_status] = dti(u_in) %#codegen % Discrete Time Integrator in MATLAB % % Forward Euler method, also known as Forward Rectangular, or left-hand % approximation. The resulting expression for the output of the block at % step 'n' is y(n) = y(n-1) + K * u(n-1) % init_val = 1; gain_val = 1; limit_upper = 500; limit_lower = -500; % variable to hold state between consecutive calls to this block persistent u_state if isempty(u_state) u_state = init_val+1; end % Compute Output if (u_state > limit_upper) y = limit_upper; clip_status = -2; elseif (u_state >= limit_upper) y = limit_upper; clip_status = -1; elseif (u_state < limit_lower) y = limit_lower; clip_status = 2; elseif (u_state <= limit_lower) y = limit_lower; clip_status = 1; else y = u_state; clip_status = 0; end % Update State tprod = gain_val * u_in; u_state = y + tprod; 14-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion function b = subFunction(a) b = a*a; The dti_test Function The test script runs the dti function with a sine wave input. The script then plots the input and output signals. % dti_test % cleanup clear dti % input signal x_in = sin(2.*pi.*(0:0.001:2)).'; pause(10) len = length(x_in); y_out = zeros(1,len); is_clipped_out = zeros(1,len); for ii = 1:len data = x_in(ii); % call to the dti function init_val = 0; gain_val = 1; upper_limit = 500; lower_limit = -500; % call to the design that does DTI [y_out(ii), is_clipped_out(ii)] = dti(data); end figure('Name', [mfilename, '_plot']) subplot(2,1,1) plot(1:len,x_in) xlabel('Time') ylabel('Amplitude') title('Input Signal (Sin)') subplot(2,1,2); plot(1:len,y_out) xlabel('Time') 14-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function ylabel('Amplitude') title('Output Signal (DTI)') disp('Test complete.') Check Code Generation Readiness In the current working folder, right-click the dti.m function. From the context menu, select Check Code Generation Readiness. The code generation readiness tool screens the code for features and functions that are not supported for code generation. The tool reports that the dti.m function is already suitable for code generation. If your entry-point function is not suitable for code generation, the tool provides a report that lists the source files that contain unsupported features and functions. The report also provides an indication of how much work you must do to make the MATLAB code ready for code generation. Before proposing data types, you must fix these issues. For more information, see “MATLAB Code Analysis”. Create and set up a MATLAB Coder Project 1 Navigate to the work folder that contains the file for this example. 2 On the MATLAB Apps tab, select MATLAB Coder and then, in the MATLAB Coder Project dialog box, set Name to dti.prj. Alternatively, at the MATLAB command line, enter coder -new dti.prj 14-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion By default, the project opens in the MATLAB workspace. 3 On the project Overview tab, click the Add files link. Browse to the file dti.m and then click OK to add the file to the project. Define Input Types 1 On the project Overview tab, click the Autodefine types link. 2 In the Autodefine Input Types dialog box, add dti_test as a test file and then click Run. The test file runs and displays the outputs of the filter for each of the input signals. 14-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function MATLAB Coder determines the input types from the test file and then displays them. 3 In the Autodefine Input Types dialog box, click Use These Types. MATLAB Coder sets the type of x to double(1x1). 14-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Fixed-Point Conversion 1 On the project Overview tab Fixed-Point Conversion pane, select Convert to fixed-point at build time. The project indicates that you must first define the fixed-point data types. 14-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function 2 In the Fixed-Point Conversion pane, click Define and validate fixed-point types. The Fixed-Point Conversion window opens and the tool generates an instrumented MEX function for your entry-point MATLAB function. After generating the MEX function, the tool displays compiled information — type, size, and complexity — for variables in your code. For more information, see “View and Modify Variable Information”. 14-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion If the MEX function generation fails, the tool provides error message links to help you navigate to the code that caused the build issues. If your code contains functions that are not supported for fixed-point conversion, the tool displays these on the Function Replacements tab. For more information, see “Running a Simulation”. 3 In the Fixed-Point Conversion window, on the Variables tab, for input u_in, select Static Min and set it to -1. Then set Static Max to 1. To compute derived range information, at a minimum you must specify static minimum and maximum values or proposed data types for all input variables. 14-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function Note: If you manually enter static ranges, these manually-entered ranges take precedence over simulation ranges and the tool uses them to propose data types. In addition, you can also modify and lock the proposed type. 4 Click the Compute Derived Ranges button. Range analysis computes the derived ranges and displays them in the Variables tab. Using these derived ranges, the analysis proposes fixed-point types for each variable based on the default type proposal settings, and displays them in the Proposed Type column. The Validate Types option is now enabled. In the dti function, the clip_status output has a minimum value of -2 and a maximum of 2. % Compute Output if (u_state > limit_upper) y = limit_upper; clip_status = -2; elseif (u_state >= limit_upper) y = limit_upper; clip_status = -1; elseif (u_state < limit_lower) y = limit_lower; clip_status = 2; elseif (u_state <= limit_lower) y = limit_lower; clip_status = 1; else y = u_state; clip_status = 0; end When you derive ranges, the Fixed-Point Conversion tool analyses the function and computes these minimum and maximum values for clip_status. 14-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion The tool provides a Quick derived range analysis option and the option to specify a timeout in case the analysis takes a very long time. For more information, see “Computing Derived Ranges” 5 To validate the build using the proposed types, click Validate Types. The software validates the proposed types, displays a Validation succeeded message, and enables the Test Numerics option. The project indicates that you have validated the fixed-point data types. 14-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function If the errors or warnings occur during validation, they are displayed on the Type Validation Output tab. For more information, see “Validating Types”. 6 Use the Simulation Data Inspector to plot the floating-point and fixed-point results. a Click b Expand the Plotting and Reporting settings and set Plot with Simulation Data Inspector to Yes. 14-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 7 Click Test Numerics, select Log inputs and outputs for comparison plots, and then click the Test Numerics button. The tool runs the test file that you used to define input types to test the fixed-point MATLAB code. Optionally, you can add test files and select to run more than one test file to test numerics. The software runs both a floating-point and a fixed-point simulation and then calculates the errors for the output variable y. Because you selected to log inputs and outputs for comparison plots and to use the Simulation Data Inspector for these plots, the Simulation Data Inspector opens. 14-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function On the Verification Output tab, the tool provides a link to a type proposal report. 14-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 8 You can use the Simulation Data Inspector to view floating-point and fixed-point run information and compare results. For example, to compare the floating-point and fixed-point values for the output y, on the Compare tab, select y, and then click Compare Runs. The Simulation Data Inspector displays a plot of the baseline floating-point run against the fixed-point run and the difference between them. 14-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function Generate Fixed-Point C Code 1 In the MATLAB Coder project, select the Build tab. 2 On this tab, set the Output type to C/C++ Static library. The default output file name is dti. 3 Click Build to generate a library using the default project settings. MATLAB Coder builds the project and generates a C static library and supporting files in the default subfolder, codegen/lib/dti_fixpt. 4 To view the generated code, click View report. The code generation report opens and displays the generated code for dti_fixpt.c. In the generated C code, variables are assigned fixed-point data types. 14-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Type Proposal Settings Basic Type Proposal Settings Values Description Fixed-point type proposal mode Propose fraction lengths for Use the specified word specified word length length for data type proposals and propose the minimum fraction lengths to avoid overflows. Propose word lengths for specified fraction length (default) Use the specified fraction length for data type proposals and propose the minimum word lengths to avoid overflows. Default word length 16 (default) Default word length to use when Fixed point type proposal mode is set to Propose fraction lengths for specified word lengths Default fraction length 4 (default) Default fraction length to use when Fixed point type proposal mode is set to Propose word lengths for specified fraction lengths Advanced Type Proposal Settings Values Description When proposing types ignore simulation ranges Propose data types based on derived ranges. ignore derived Note: Manually-entered static ranges ranges always take precedence over simulation use all collected data ranges. (default) Propose data types based on simulation ranges. Propose target container types Propose data type with the smallest word length that can represent the range and is suitable for C code generation ( 8,16,32, 64 … ). For Yes 14-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Propose data types based on both simulation and derived ranges. Type Proposal Settings Advanced Type Proposal Settings Optimize whole numbers Signedness Safety margin for sim min/max (%) Values Description example, for a variable with range [0..7], propose a word length of 8 rather than 3. No (default) Propose data types with the minimum word length needed to represent the value. No Do not use integer scaling for variables that were whole numbers during simulation. Yes (default) Use integer scaling for variables that were whole numbers during simulation. Automatic (default) Proposes signed and unsigned data types depending on the range information for each variable. Signed Propose signed data types. Unsigned Propose unsigned data types. 0 (default) Specify safety factor for simulation minimum and maximum values. The simulation minimum and maximum values are adjusted by the percentage designated by this parameter, allowing you to specify a range different from that obtained from the simulation run. For example, a value of 55 specifies that you want a range at least 55 percent larger. A value of -15 specifies that a range up to 15 percent smaller is acceptable. fimath Settings Values Description Rounding method Ceiling Specify the fimath properties for the generated fixed-point data types. Convergent 14-35 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion fimath Settings Values Floor (default) Nearest Round Zero Overflow action Saturate Wrap (default) Product mode FullPrecision (default) KeepLSB KeepMSB SpecifyPrecision Sum mode FullPrecision (default) KeepLSB KeepMSB Description The default fixed-point math properties use the Floor rounding and Wrap overflow because they are the default actions in C. These settings generate the most efficient code but might cause problems with overflow. After code generation, if required, modify these settings to optimize the generated code, or example, avoid overflow or eliminate bias, and then rerun the verification. SpecifyPrecision Product word length 32 (default)|any positive integer Word length, in bits, of the product data type Sum word length 32 (default)|any positive integer Word length, in bits, of the sum data type Generated File Settings Value Description Generated fixed-point file name suffix _fixpt (default) Specify the suffix to add to the generated fixed-point file names. For example, by default, if you generate a static library for a project named test, the generated files are in the subfolder codegen\lib\test_fixpt. The generated static library is named test.lib, but the generated C code files 14-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Type Proposal Settings Generated File Settings Value Description use the suffix, for example, test_fixpt.c. Plotting and Reporting Settings Values Description Custom plot function Empty string Specify the name of a custom plot function to use for comparison plots. Plot with Simulation Data Inspector No (default) Specify whether to use the Simulation Data Inspector for comparison plots. Highlight potential data type issues No (default) Yes Yes Specify whether to highlight potential data types in the generated html report. If this option is turned on, the report highlights singleprecision, double-precision, and expensive fixed-point operation usage in your MATLAB code. 14-37 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Detect Overflows This example shows how to detect overflows using the Fixed-Point Conversion tool. At the numerical testing stage in the conversion process, the tool simulates the fixedpoint code using scaled doubles. It then reports which expressions in the generated code produce values that would overflow the fixed-point data type. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer Create a Project In a local writable folder, create a MATLAB Coder project named overflow. At the MATLAB command line, enter coder -new overflow.prj By default, the project opens in the MATLAB workspace. Add File 1 In the same folder, create a function, overflow. function y = overflow(b,x,reset) if nargin<3, reset = true; end persistent z p if isempty(z) || reset p = 0; z = zeros(size(b)); end [y,z,p] = fir_filter(b,x,z,p); end function [y,z,p] = fir_filter(b,x,z,p) y = zeros(size(x)); nx = length(x); nb = length(b); for n = 1:nx p=p+1; if p>nb, p=1; end 14-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Detect Overflows z(p) = x(n); acc = 0; k = p; for j=1:nb acc = acc + b(j)*z(k); k=k-1; if k<1, k=nb; end end y(n) = acc; end end 2 On the project Overview tab, click the Add files link. Browse to the file overflow.m and then click OK to add the file to the project. Define Input Types 1 Create a test file, overflow_test.m to exercise the overflow algorithm. You use this test file to define input types for b, x, and reset, and, later, to verify the fixedpoint version of the algorithm. function overflow_test % The filter coefficients were computed using the FIR1 function from % Signal Processing Toolbox. % b = fir1(11,0.25); b = [-0.004465461051254 -0.004324228005260 +0.012676739550326 +0.074351188907780 +0.172173206073645 +0.249588554524763 +0.249588554524763 +0.172173206073645 +0.074351188907780 +0.012676739550326 -0.004324228005260 -0.004465461051254]'; % Input signal nx = 256; t = linspace(0,10*pi,nx)'; % Impulse x_impulse = zeros(nx,1); x_impulse(1) = 1; % Max Gain 14-39 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion % The maximum gain of a filter will occur when the inputs line up with the % signs of the filter's impulse response. x_max_gain = sign(b)'; x_max_gain = repmat(x_max_gain,ceil(nx/length(b)),1); x_max_gain = x_max_gain(1:nx); % Sums of sines f0=0.1; f1=2; x_sines = sin(2*pi*t*f0) + 0.1*sin(2*pi*t*f1); % Chirp f_chirp = 1/16; x_chirp = sin(pi*f_chirp*t.^2); % Target frequency % Linear chirp x = [x_impulse, x_max_gain, x_sines, x_chirp]; titles = {'Impulse', 'Max gain', 'Sum of sines', 'Chirp'}; y = zeros(size(x)); for i=1:size(x,2) reset = true; y(:,i) = overflow(b,x(:,i),reset); end test_plot(1,titles,t,x,y) end function test_plot(fig,titles,t,x,y1) figure(fig) clf sub_plot = 1; font_size = 10; for i=1:size(x,2) subplot(4,1,sub_plot) sub_plot = sub_plot+1; plot(t,x(:,i),'c',t,y1(:,i),'k') axis('tight') xlabel('t','FontSize',font_size); title(titles{i},'FontSize',font_size); ax = gca; ax.FontSize = 10; end figure(gcf) end 14-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Detect Overflows 2 3 On the project Overview tab, click the Autodefine types link. In the Autodefine Input Types dialog box, add overflow_test as a test file and then click Run. The test file runs and displays the outputs of the filter for each of the input signals.MATLAB Coder determines the input types from the test file and then displays them. 4 In the Autodefine Input Types dialog box, click Use These Types. MATLAB Coder sets the types of b to double(1x12), x to double(256x1), and reset to logical(1x1). Fixed-Point Conversion 1 On the project Overview tab Fixed-Point Conversion pane, select Convert to fixed-point at build time. The project indicates that you must first define the fixed-point data types. 2 In the Fixed-Point Conversion pane, click Define and validate fixed-point types. The Fixed-Point Conversion tool opens and generates an instrumented MEX function for your entry-point MATLAB function. After generating the MEX function, the tool displays compiled information — type, size, and complexity — for variables in your code. For more information, see “View and Modify Variable Information”. 3 In the Fixed-Point Conversion tool, click Advanced to view the advanced settings. Set the fimath Product mode and Sum mode to KeepLSB. These settings models the behavior of integer operations in the C language. 14-41 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 4 In the Fixed-Point Conversion tool, click Run Simulation and verify that the overflow_test file is selected as the test file to run and then click the Run Simulation button. The simulation runs and the conversion tool displays simulation minimum and maximum ranges on the Variables tab. Using the simulation range data, the software proposes fixed-point types for each variable based on the default type proposal settings, and displays them in the Proposed Type column. The Validate Types option is now enabled. 5 To validate the build using the proposed types, click Validate Types. The software validates the proposed types, displays a Validation succeeded message, and enables the Test Numerics option. If the errors or warnings occur during validation, they are displayed on the Type Validation Output tab. For more information, see “Validating Types”. Test Numerics and Check for Overflows 1 Click Test Numerics, select Use scaled doubles to detect overflows, and then click the Test Numerics button. 14-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Detect Overflows The tool runs the test file that you used to define input types to test the fixed-point MATLAB code. Because you selected to detect overflows, it also runs the simulation using scaled double versions of the proposed fixed-point types. Scaled doubles store their data in double-precision floating-point, so they carry out arithmetic in full range. They also retain their fixed-point settings, so they are able to report when a computation goes out of the range of the fixed-point type. The simulation runs and the tool detects an overflow. The tool reports on the Overflow tab and highlights the expression that overflowed in the code window. 2 Determine whether it was the sum or the multiplication that overflowed. 14-43 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion In the Advanced settings, set Product mode to FullPrecision, and then click Test Numerics. The overflow still occurs, indicating that it is the addition in the expression that is overflowing. 14-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace the exp Function with a Lookup Table Replace the exp Function with a Lookup Table This example shows how to replace the exp function with a lookup table approximation in fixed-point code generated using the Fixed-Point Conversion tool. Create Algorithm and Test Files 1 Create a MATLAB function, my_fcn, that calls the exp function. function y = my_fcn(x) y = exp(x); end 2 Create a test file, my_fcn_test, that uses my_fcn. close all x = linspace(-10,10,1e3); for itr = 1e3:-1:1 y(itr) = my_fcn( x(itr) ); end plot( x, y ); Create and Set Up a MATLAB Coder Project 1 Navigate to the work folder that contains the file for this example. 2 On the MATLAB Apps tab, select MATLAB Coder and then, in the MATLAB Coder Project dialog box, set Name to fun_with_matlab_project.prj. Alternatively, at the MATLAB command line, enter coder -new my_fcn_project.prj By default, the project opens in the MATLAB workspace. 3 On the project Overview tab, click the Add files link. Browse to the file my_fcn.m and then click OK to add the file to the project. Define Input Types 1 On the project Overview tab, click the Autodefine types link. 2 In the Autodefine Input Types dialog box, add my_fcn_test as a test file and then click Run. The test file runs and plots the output. 14-45 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 3 MATLAB Coder determines from the test file that x is a scalar double. 4 In the Autodefine Input Types dialog box, click Use These Types. MATLAB Coder sets the type of x to double(1x1). 14-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace the exp Function with a Lookup Table Fixed-Point Conversion 1 On the project Overview tab Fixed-Point Conversion pane, select Convert to fixed-point at build time. The project indicates that you must first define the fixed-point data types. 2 In the Fixed-Point Conversion pane, click Define and validate fixed-point types. The Fixed-Point Conversion window opens and the tool generates an instrumented MEX function for your entry-point MATLAB function. After generating the MEX function, the tool displays compiled information — type, size, and complexity — for variables in your code. The tool displays functions in your original algorithm that are not supported for fixed-point conversion on the Function Replacements tab. 14-47 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 3 On the Function Replacements tab, right-click the exp function and select Lookup Table. The tool moves the exp function to the list of functions that it will replace with a Lookup Table. By default, the lookup table uses linear interpolation, 1000 points, and the design minimum and maximum values that the tool detects by either running a simulation or computing derived ranges. 4 Click Run Simulation, select Log data for histogram, and verify that the my_fcn_test file is selected as a test file to run. 5 Click the Run Simulation button, 14-48 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace the exp Function with a Lookup Table The simulation runs and the tool displays simulation minimum and maximum ranges on the Variables tab. Using the simulation range data, the software proposes fixed-point types for each variable based on the default type proposal settings, and displays them in the Proposed Type column. The Validate Types option is now enabled. 6 Examine the proposed types and verify that they cover the full simulation range. To view logged histogram data for a variable, click its Proposed Type field. The histogram provides range information and the percentage of simulation range covered by the proposed data type. 7 To validate the build using the proposed types, click Validate Types. The software validates the proposed types and generates a fixed-point function, my_fcn_fixpt. 8 On the Type Validation Output tab, click the my_fcn_fixpt link to view the generated fixed-point code. The conversion process generates a lookup table approximation, exp1, for the exp function. The generated fixed-point function, my_fcn_fixpt, calls this approximation instead of calling exp. function y = my_fcn_fixpt(x) fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128, ... 14-49 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi(exp1(x), 0, 16, 1, fm); end You can now test the generated fixed-point code and compare the results against the original MATLAB function. If the behavior of the generated fixed-point code does not match the behavior of the original code closely enough, modify the interpolation method or number of points used in the lookup table and then regenerate code. 14-50 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace a Custom Function with a Lookup Table Replace a Custom Function with a Lookup Table This example shows how to replace a custom function with a lookup table approximation function using the Fixed-Point Conversion tool. Create Algorithm and Test Files In a local, writable folder: 1 Create a MATLAB function, custom_fcn which is the function that you want to replace. function y = custom_fcn(x) y = 1./(1+exp(-x)); end 2 Create a wrapper function that calls custom_fcn. function y = call_custom_fcn(x) y = custom_fcn(x); end 3 Create a test file, custom_test, that uses call_custom_fcn. close all x = linspace(-10,10,1e3); for itr = 1e3:-1:1 y(itr) = call_custom_fcn( x(itr) ); end plot( x, y ); Create and Set Up a MATLAB Coder Project 1 Navigate to the work folder that contains the file for this example. 2 On the MATLAB Apps tab, select MATLAB Coder and then, in the MATLAB Coder Project dialog box, set Name to custom_project.prj. Alternatively, at the MATLAB command line, enter coder -new custom_project.prj By default, the project opens in the MATLAB workspace. 3 On the project Overview tab, click the Add files link. Browse to the file call_custom_fcn.m and then click OK to add the file to the project. 14-51 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Define Input Types 1 On the project Overview tab, click the Autodefine types link. 2 In the Autodefine Input Types dialog box, add custom_test as a test file and then click Run. The test file runs and plots the output. 3 MATLAB Coder determines from the test file that x is a scalar double. 14-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace a Custom Function with a Lookup Table 4 In the Autodefine Input Types dialog box, click Use These Types. MATLAB Coder sets the type of x to double(1x1). Fixed-Point Conversion 1 On the project Overview tab Fixed-Point Conversion pane, select Convert to fixed-point at build time. The project indicates that you must first define the fixed-point data types. 2 In the Fixed-Point Conversion pane, click Define and validate fixed-point types. The Fixed-Point Conversion window opens and the tool generates an instrumented MEX function for your entry-point MATLAB function. After generating the MEX function, the tool displays compiled information — type, size, and complexity — for variables in your code. 3 Select the Function Replacements tab. 14-53 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 4 Enter the name of the function to replace, custom_fcn, select Lookup Table, and then click +. 14-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace a Custom Function with a Lookup Table The tool adds custom_fcn to the list of functions that it will replace with a Lookup Table. By default, the lookup table uses linear interpolation, 1000 points, and the design minimum and maximum values that the app detects by either running a simulation or computing derived ranges. 14-55 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 5 Click Run Simulation, select Log data for histogram and verify that the custom_test file is selected as a test file to run. 6 Click the Run Simulation button. The simulation runs and the tool displays simulation minimum and maximum ranges on the Variables tab. Using the simulation range data, the software proposes fixed-point types for each variable based on the default type proposal settings, and displays them in the Proposed Type column. The Validate Types option is now enabled. 7 Examine the proposed types and verify that they cover the full simulation range. To view logged histogram data for a variable, click its Proposed Type field. The 14-56 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace a Custom Function with a Lookup Table histogram provides range information and the percentage of simulation range covered by the proposed data type. 8 To validate the build using the proposed types, click Validate Types. The software validates the proposed types and generates a fixed-point code, call_custom_fcn_fixpt. 9 On the Type Validation Output tab, click the call_custom_fcn_fixpt link to view the generated fixed-point code. The conversion process generates a lookup table approximation, custom_fcn1, for the custom_fcn function. The generated fixed-point function, call_custom_fcn_fixpt.m, calls this approximation instead of calling custom_fcn. function y = call_custom_fcn_fixpt(x) fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128,... 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi(custom_fcn1(x), 0, 16, 16, fm); end You can now test the generated fixed-point code and compare the results against the original MATLAB function. 14-57 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Enable Plotting Using the Simulation Data Inspector You can use the Simulation Data Inspector to inspect and compare floating-point and fixed-point logged input and output data. In the Fixed-Point Conversion tool: 1 Click Advanced. 2 In the Advanced Settings dialog box, set Plot with Simulation Data Inspector to Yes. 3 At the Test Numerics stage in the conversion process, click Test Numerics, select Log inputs and outputs for comparison plots, and then click . For an example, see “Propose Fixed-Point Data Types Based on Derived Ranges”. 14-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Log Data for Histogram Log Data for Histogram To log data for histograms: 1 In the Fixed-Point Conversion window, click Run Simulation and select Log data for histogram, and then click the Run Simulation button. The simulation runs and the simulation minimum and maximum ranges are displayed on the Variables tab. Using the simulation range data, the software proposes fixed-point types for each variable based on the default type proposal settings, and displays them in the Proposed Type column. 2 To view a histogram for a variable, click the variable’s Proposed Type field. 14-59 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 3 You can view the effect of changing the proposed data types by: • Selecting and dragging the white bounding box in the histogram window. This action does not change the word length of the proposed data type, but modifies 14-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Log Data for Histogram the position of the binary point within the word so that the fraction length of the proposed data type changes. • Selecting and dragging the left edge of the bounding box to increase or decrease the word length. This action does not change the fraction length or the position of the binary point. • Selecting and dragging the right edge to increase or decrease the fraction length of the proposed data type. This action does not change the position of the binary point. The word length changes to accommodate the fraction length. • Selecting or clearing Signed. Clear Signed to ignore negative values. Before committing changes, you can revert to the types proposed by the automatic conversion by clicking . 14-61 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion View and Modify Variable Information View Variable Information To view information about the variables in the MATLAB function selected in the Navigation pane, use the Variables tab or place your cursor over a variable in the code window. For more information, see “Viewing Variables” on page 14-94. You can view the variable information: • Variable Variable name. Variables are classified and sorted as inputs, outputs, persistent, or local variables. • Type The original size, type, and complexity of each variable. • Sim Min The minimum value assigned to the variable during simulation. • Sim Max The maximum value assigned to the variable during simulation. To search for variables in the MATLAB code pane and on the Variables tab, use Ctrl +F. The tool highlights occurrences in the code and displays only the variable with the specified name on the Variables tab. Modify Variable Information If you modify variable information, the tool highlights the values in bold. You can modify the following fields: • Static Min You can enter a value for Static Min into the field or promote Sim Min information. See “Promote Sim Min and Sim Max Values” on page 14-65. Editing this field does not trigger static range analysis, but the tool uses the edited values in subsequent analyses. 14-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان View and Modify Variable Information • Static Max You can enter a value for Static Max into the field or promote Sim Max information. See “Promote Sim Min and Sim Max Values” on page 14-65. Editing this field does not trigger static range analysis, but the tool uses the edited values in subsequent analyses. • Whole Number The Fixed-Point Conversion tool uses simulation data to determine whether the values assigned to a variable during simulation were always integers. You can manually override this field. Editing this field does not trigger static range analysis, but the tool uses the edited value in subsequent analyses. • Proposed Type You can modify the signedness, word length, and fraction length settings individually by: • On the Variables tab, by modifying the value in the ProposedType field. • In the code window, by selecting a variable and then modifying the ProposedType field. 14-63 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion If you selected to log data for a histogram, the histogram dynamically updates to reflect the modifications to the proposed type. You can also modify the proposed type in the histogram, see “Histogram” on page 14-100. Revert Changes • To clear results and revert edited values, right-click the Variables tab and select Reset entire table. • To revert the type of a selected variable to the type computed by the tool, right-click the field and select Undo changes. • To revert changes to variables, right-click the field and select Undo changes for all variables. 14-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان View and Modify Variable Information • To clear a static range value, right-click an edited field and select Clear static range. • To clear manually-entered static range values, right-click anywhere on the Variables tab and select Clear all manually entered static ranges. Promote Sim Min and Sim Max Values The Fixed-Point Conversion tool allows you to promote simulation minimum and maximum values to static minimum and maximum values. This capability is useful if you have not specified static ranges and you have simulated the model with inputs that cover the full intended operating range. To copy: • A simulation range for a selected variable, select a variable, right-click and then select Copy sim range. • Simulation ranges for top-level inputs, right-click the Static Min or Static Max column and then select Copy sim ranges for all top-level inputs. • Simulation ranges for persistent variables, right-click the Static Min or Static Max column and then select Copy sim ranges for all persistent inputs. 14-65 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Build Instrumented MEX Function Note: This capability is not compatible with automatic fixed-point conversion. If you select Convert to fixed point at build time, you cannot build instrumented MEX functions. 1 In the project, click the Build tab. 2 On the Build tab, set the Output type to Instrumented MEX Function. 3 Click the Build button. The Build progress dialog box opens. When the build is complete, MATLAB Coder generates an instrumented MEX function in the current folder. It also provides a link to the report on the Show Instrumentation Results pane. In this report, you can view the types of variables in your MATLAB code. After you run the instrumented MEX function, the instrumentation report provides fixed-point data type proposals based on the simulation range data. You can use this information to convert your MATLAB code to fixed point by hand. For more information, see “Propose Fixed-Point Data Types” on page 14-67 14-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Propose Fixed-Point Data Types Propose Fixed-Point Data Types This example shows how to propose fixed-point data types using an instrumented MEX function. This capability is not compatible with automatic fixed-point conversion. If you select Convert to fixed point at build time, you cannot build instrumented MEX functions. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a New Folder and Copy Relevant Files 1 Create a local working folder, for example, c:\coder\fun_with_matlab. 2 Change to the docroot\toolbox\coder\examples folder. At the MATLAB command line, enter: cd(fullfile(docroot, 'toolbox', 'coder', 'examples')) 3 Copy the fun_with_matlab.m and fun_with_matlab_test.m files to your local working folder. Type Name Description Function code fun_with_matlab.m Entry-point MATLAB function Test file fun_with_matlab_test.m MATLAB script that tests fun_with_matlab.m 14-67 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion The fun_with_matlab Function function y = fun_with_matlab(x) %#codegen persistent z if isempty(z) z = zeros(2,1); end % [b,a] = butter(2, 0.25) b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175]; a = [1, -0.942809041582063, 0.3333333333333333]; y = zeros(size(x)); for i = 1:length(x) y(i) = b(1)*x(i) + z(1); z(1) = b(2)*x(i) + z(2) - a(2) * y(i); z(2) = b(3)*x(i) - a(3) * y(i); end end Check Code Generation Readiness In the current working folder, right-click the fun_with_matlab.m function. From the context menu, select Check Code Generation Readiness. The code generation readiness tool screens the code for features and functions that are not supported for code generation. The tool reports that the fun_with_matlab.m function is already suitable for code generation. If your entry-point function is not suitable for code generation, the tool provides a report that lists the source files that contain unsupported features and functions. The report 14-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Propose Fixed-Point Data Types also provides an indication of how much work you must do to make the MATLAB code ready for code generation. Before proposing data types, you must fix these issues. For more information, see “MATLAB Code Analysis”. Create and set up a MATLAB Coder Project 1 Navigate to the work folder that contains the file for this tutorial. 2 On the MATLAB Apps tab, select MATLAB Coder and then, in the MATLAB Coder Project dialog box, set Name to fun_with_matlab_project.prj. Alternatively, at the MATLAB command line, enter coder -new fun_with_matlab_project.prj By default, the project opens in the MATLAB workspace. 14-69 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion 3 On the project Overview tab, click the Add files link. Browse to the file fun_with_matlab.m and then click OK to add the file to the project. About the fun_with_matlab_test Script The test script runs the fun_with_matlab function with three input signals: chirp, step, and impulse. The script then plots the results. 14-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Contents of fun_with_matlab_test Contents of fun_with_matlab_test % fun_with_matlab_test % % Define representative inputs % Number of points N = 256; t = linspace(0,1,N); % Time vector from 0 to 1 second f1 = N/2; % Target frequency of chirp set to Nyquist x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second % Step x_step = ones(1,N); x_impulse = zeros(1,N); % Impulse x_impulse(1) = 1; % Run the function under test x = [x_chirp;x_step;x_impulse]; y = zeros(size(x)); for i = 1:size(x,1) y(i,:) = fun_with_matlab(x(i,:)); end % Plot the results titles = {'Chirp','Step','Impulse'}; clf for i = 1:size(x,1) subplot(size(x,1),1,i) plot(t,x(i,:),t,y(i,:)) title(titles{i}) legend('Input','Output') end xlabel('Time (s)') figure(gcf) disp('Test complete.') Define Input Types 1 On the project Overview tab, click the Autodefine types link. 2 In the Autodefine Input Types dialog box, add fun_with_matlab_test as a test file and then click Run. The test file runs and displays the outputs of the filter for each of the input signals. 14-71 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion MATLAB Coder determines the input types from the test file and then displays them in the Autodefine Input Types dialog box. 3 In this dialog box, click Use These Types. MATLAB Coder sets the type of x to double(1x256). 14-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Contents of fun_with_matlab_test Build Instrumented MEX Function 1 In the project, click the Build tab. 2 On the Build tab, set the Output type to Instrumented MEX Function. 3 Click the Build button. The Build progress dialog box opens. When the build is complete, MATLAB Coder generates an instrumented MEX function fun_with_matlab_mex in the current folder. It also provides a link to the report on the Show Instrumentation Results pane. In this report, you can view the types of variables in your MATLAB code. View Data Type Proposal Settings 1 On the Show Instrumentation Results pane, click the Data type proposal and report settings link. 14-73 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion This example uses the default data type proposal settings which propose fraction lengths for the specified word lengths. Because the MATLAB code is floatingpoint, the word length is specified by the Default data type of all floating-point expressions field. You can specify the numerictype signedness, word length and fraction length. Specifying [] for signedness instructs MATLAB Coder to choose the signedness based on simulation values. The default word length is 16. The default fraction length is 12. For more information, see “Modify Data Type Proposal Settings”. 14-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Contents of fun_with_matlab_test 2 Close the dialog box. Run Simulation 1 On the Run Simulation pane, verify that the test file is set to fun_with_matlab_test and that Redirect entry-point calls to MEX function is selected. That way, each call to fun_with_matlab is replaced with a call to the instrumented MEX function fun_with_matlab_mex. 2 On the Run Simulation pane, click Run. The fun_with_matlab_test file runs and calls fun_with_matlab_mex. The outputs of the filters are displayed as before. View Code Generation Report 1 On the Show Instrumentation Results pane, click View Report. 2 In the Code Generation Report, click the Variables tab. The report displays the simulation minimum and maximum values and the proposed data types. 14-75 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion MATLAB Coder proposes data types with word length of 16 and fraction length optimized to avoid overflows. Next Steps To learn how to apply the proposed data types to your entry-point MATLAB function and verify that the fixed-point version of your algorithm is functionally equivalent to your original MATLAB algorithm, see “Apply Fixed-Point Data Types”. 14-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Apply Fixed-Point Data Types Apply Fixed-Point Data Types This example shows how to write a fixed-point version of your entry-point function using the data types proposed in “Propose Fixed-Point Data Types”. This capability is not compatible with automatic fixed-point conversion. If you select Convert to fixed point at build time, you cannot build instrumented MEX functions. You will learn how to: • Use the proposed data types to create a fixed-point version of your entry-point function. • Update your test file to call the fixed-point entry-point function. • Verify that the fixed-point function is functionally equivalent to the original MATLAB algorithm. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a New Folder and Copy Relevant Files 1 Create a local working folder, for example, c:\coder\fun_with_matlab. 2 Change to the docroot\toolbox\coder\examples folder. At the MATLAB command line, enter: cd(fullfile(docroot, 'toolbox', 'coder', 'examples')) 3 Copy the following files to your local working folder. 14-77 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Type Name Description Function code fun_with_matlab.m Entry-point MATLAB function Test file fun_with_matlab_test.m MATLAB script that tests fun_with_matlab.m Function code fun_with_fi.m Entry-point MATLAB function — fixed-point version of fun_with_matlab that uses data types proposed in “Propose FixedPoint Data Types” Test file fun_with_fi_test.m MATLAB script that runs both fun_with_matlab and fun_with_fi and compares the results The fun_with_fi Function The fun_with_fi is a fixed-point version of the fun_with_matlab function that uses the data types proposed in “Propose Fixed-Point Data Types”. Variable Proposed Signedness Proposed Word Length Proposed Fraction Length y Signed 16 14 x Signed 16 14 z Signed 16 15 a Unsigned 16 18 b Signed 16 14 i Unsigned 16 0 For example, in fun_with_matlab, variable y is defined as y = zeros(size(x));. In fun_with_fi, to specify that it is a signed fixed-point data type with a word length of 16 and a fraction length of 14: y = fi(zeros(size(x)),1,16,14,'OverflowAction','Wrap','RoundingMethod','Floor'); For more information, see fi. 14-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Apply Fixed-Point Data Types Create and set up a MATLAB Coder Project 1 Navigate to the work folder that contains the file for this tutorial. 2 On the MATLAB Apps tab, select MATLAB Coder and then, in the MATLAB Coder Project dialog box, set Name to fun_with_fi_project.prj. Alternatively, at the MATLAB command line, enter coder -new fun_with_fi_project.prj By default, the project opens in the MATLAB workspace. 3 On the project Overview tab, click the Add files link. Browse to the file fun_with_fi.m, and then click OK to add the file to the project. Define Input Types 1 On the project Overview tab, click the Autodefine types link. 2 In the Autodefine Input Types dialog box, add fun_with_fi_test as a test file, and then click Run. 14-79 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion The test file runs and plots the outputs of the filter. MATLAB Coder determines the input types from the test file and then displays them. 3 In the Autodefine Input Types dialog box, click Use These Types to accept the autodefined input type. MATLAB Coder sets the type of x to double(1x256). The fun_with_fi_test Script The fun_with_fi_test script runs the original floating-point MATLAB algorithm, fun_with_matlab, then runs the fixed-point version of the algorithm, fun_with_fi. The script then plots the outputs for the floating-point and fixed-point algorithms and the difference in results. Run Simulation 1 In the project, click the Build tab. 2 On the Verification pane, verify that the test file is set to fun_with_fi_test. Clear Redirect entry-point calls to MEX function so that the test file calls the MATLAB versions of the original and fixed-point algorithms. 3 On Verification pane, click Run. The fun_with_fi_test file runs. The test file runs the original MATLAB algorithm and the fixed-point version, and plots the difference in their outputs. 14-80 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Apply Fixed-Point Data Types 4 Optionally, zoom in on each plot in turn to view the error (difference between the two versions of the algorithm). In this example, the errors are very small, on the order of -3 10 . If the error is unacceptably large, refine the fixed-point data types. 14-81 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Modify Data Type Proposal Settings When generating instrumented MEX functions, to modify data type proposal settings, on the project Build tab, on the Show Instrumentation Results pane, click Data type proposal and report settings. Type Proposal Setting Description Propose data types Specify whether to propose data types based on simulation minimum and maximum values. You can view the proposed data types in the code generation report. Dependencies: • This parameter enables: • Propose fraction lengths for specified word lengths • Propose word lengths for specified fraction lengths • Default data type of all floating-point expressions • Safety margin for min/max values • Optimize whole numbers Propose fraction Select to propose fraction lengths for the word lengths specified in the code. lengths for Use simulation minimum and maximum information to propose fraction specified word lengths for variables in your entry-point MATLAB function. MATLAB Coder lengths proposes data types for variables that are scaled doubles and built-in data types only. For floating-point data types in your entry-point function, uses the word length and signedness specified in Default data type of all floatingpoint expressions to determine the optimal fraction lengths. Dependency: • Clearing Propose data types disables this parameter. Propose word Select to propose word lengths for the fraction lengths specified in the code. lengths for Use simulation minimum and maximum information to propose word lengths specified fraction lengths for variables in your entry-point MATLAB function. MATLAB Coder proposes data types for variables that are scaled doubles and built-in data types only. For floating-point data types in your entry-point function, uses the fraction 14-82 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Modify Data Type Proposal Settings Type Proposal Setting Description length and signedness specified in Default data type of all floating-point expressions to determine the optimal word lengths. Dependency: • Clearing Propose data types disables this parameter. Default data type of all floating-point expressions Specify the default data type to use for floating-point expressions in your entry-point MATLAB function. MATLAB Coder uses this default data type to change the floating-point data types in the code to fixed point. Dependency: • Clearing Propose data types disables this parameter. numerictype([],16,12) Set the default data type for floating-point signals to the fixed-point data type specified by (Default) numerictype. You can modify the parameters provided to numerictype to specify signedness, word length, and fraction length. Specifying [] for signedness instructs MATLAB Coder to choose the appropriate signedness. Remain floatingpoint Do not change the data type of floating-point signals. int8 Set the default data type for floating-point signals to int8. int16 Set the default data type for floating-point signals to int16. int32 Set the default data type for floating-point signals to int32. 14-83 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Type Proposal Setting Description Safety margin for min/max values Specify safety factor for simulation minimum and maximum values. The simulation minimum and maximum values are adjusted by the percentage designated by this parameter, allowing you to specify a range different from that obtained from the simulation run. For example, a value of 55 specifies that you want a range at least 55 percent larger. A value of -15 specifies that a range up to 15 percent smaller is acceptable. Dependency: • Clearing Propose data types disables this parameter. Optimize whole numbers Specify to use integer scaling for variables that were whole numbers during simulation. Dependency: • Clearing Propose data types disables this parameter. 14-84 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Modify Instrumentation Report Settings Modify Instrumentation Report Settings When generating instrumented MEX functions, to modify instrumentation report settings, on the project Build tab, on the Show Instrumentation Results pane, click Data type proposal and report settings. Report Setting Description Automatically launch report Specify whether to automatically display the report after running the test file. after running test file Open report in a web browser Specify whether to open the report in a Web browser. Enabling this option allows you to open multiple reports simultaneously. Create printable report Specify whether to create a printable report. 14-85 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Automated Fixed-Point Conversion In this section... “License Requirements” on page 14-86 “Automated Fixed-Point Conversion Capabilities” on page 14-86 “Code Coverage” on page 14-88 “Proposing Data Types” on page 14-91 “Locking Proposed Data Types” on page 14-93 “Viewing Functions” on page 14-93 “Viewing Variables” on page 14-94 “Histogram” on page 14-100 “Function Replacements” on page 14-102 “Validating Types” on page 14-103 “Testing Numerics” on page 14-103 “Detecting Overflows” on page 14-104 License Requirements Fixed-point conversion requires the following licenses: • Fixed-Point Designer • MATLAB Coder Automated Fixed-Point Conversion Capabilities You can convert floating-point MATLAB code to fixed-point code using the Fixed-Point Conversion tool in MATLAB Coder projects. You can choose to propose data types based on simulation range data, derived (also known as static) range data, or both. You can manually enter static ranges. These manually-entered ranges take precedence over simulation ranges and the tool uses them when proposing data types. In addition, you can modify and lock the proposed type so that the tool cannot change it. For more information, see “Locking Proposed Data Types” on page 14-93. For a list of supported MATLAB features and functions, see “MATLAB Language Features Supported for Automated Fixed-Point Conversion”. 14-86 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion During fixed-point conversion, you can: • Verify that your test files cover the full intended operating range of your algorithm using code coverage results. • Propose fraction lengths based on default word lengths. • Propose word lengths based on default fraction lengths. • Optimize whole numbers. • Specify safety margins for simulation min/max data. • Validate that you can build your project with the proposed data types. • Test numerics by running the test file with the fixed-point types applied. 14-87 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion • View a histogram of bits used by each variable. • Detect overflows. Code Coverage By default, the Fixed-Point Conversion tool shows code coverage results. Your test files should exercise the algorithm over its full operating range so that the simulation ranges are accurate. The quality of the proposed fixed-point data types depends on how well the test files cover the operating range of the algorithm with the accuracy that you want. Reviewing code coverage results helps you verify that your test file is exercising the algorithm adequately. If the code coverage is inadequate, modify the test file or add more test files to increase coverage. If you simulate multiple test files in one run, the tool displays cumulative coverage. However, if you specify multiple test files but run them one at a time, the tool displays the coverage of the file that ran last. Code coverage is on by default. Turn it off only after you have verified that you have adequate test file coverage. Turning off code coverage might speed up simulation. To turn off code coverage, in the Fixed-Point Conversion tool: 1 Click Run Simulation. 2 Clear Show code coverage. The tool covers basic MATLAB control constructs and shows statement coverage for basic blocks of code. The tool displays a color-coded coverage bar to the left of the code. Coverage Bar Color How Often Code is Executed During Test File Simulation Dark green Always Light green Sometimes Orange Once Red Never 14-88 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion When you position your cursor over the coverage bar, the color highlighting extends over the code and the tool displays more information about how often the code is executed. For MATLAB constructs that affect control flow (if-elseif-else, switch-case, for-continuebreak, return), it displays statement coverage as a percentage coverage for basic blocks inside these constructs. 14-89 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion To verify that your test file is testing your algorithm over the intended operating range, review the code coverage results and take action as described in the following table. Coverage Bar Color Action Required Dark green None Light green Review percentage coverage and verify that it is reasonable based on your algorithm. If there are areas of code that you expect to be executed more frequently, modify your test file or add more test files to increase coverage. 14-90 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion Coverage Bar Color Action Required Orange This is expected behavior for initialization code, for example, the initialization of persistent variables. For other cases, verify that this behavior is reasonable for your algorithm. If there are areas of code that you expect to be executed more frequently, modify your test file or add more test files to increase coverage. Red If the code that is not executed is an error condition, this is acceptable behavior. If the code should be executed, modify the test file or add another test file to extend coverage. If the code is written conservatively and has upper and lower boundary limits and you cannot modify the test file to reach this code, add static minimum and maximum values (see “Computing Derived Ranges”). Proposing Data Types The Fixed-Point Conversion tool proposes fixed-point data types based on computed ranges and the word length or fraction length setting. The computed ranges are based on simulation range data, derived range data, or both. If you run a simulation and compute derived ranges, the conversion tool merges the simulation and derived ranges. Note: You cannot propose data types based on derived ranges for MATLAB classes. You can manually enter static ranges. These manually-entered ranges take precedence over simulation ranges and the tool uses them when proposing data types. In addition, you can modify and lock the proposed type so that the tool cannot change it. For more information, see “Locking Proposed Data Types” on page 14-93. Running a Simulation When you open the Fixed-Point Conversion tool, the tool generates an instrumented MEX function for your entry-point MATLAB file. If the build completes without errors, the tool displays compiled information (type, size, complexity) for functions and variables in your code. To navigate to local functions, click the Functions tab. If build errors occur, the tool provides error messages that link to the line of code that caused the build issues. You must address these errors before running a simulation. Use the link to navigate to the offending line of code in the MATLAB editor and modify the 14-91 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion code to fix the issue. If your code uses functions that are not supported for fixed-point conversion, the tool displays them on the Function Replacements tab. See “Function Replacements” on page 14-102. Before running a simulation, specify the test file or files that you want to run. When you run a simulation, the tool runs the test file, calling the instrumented MEX function. If you modify the MATLAB design code, the tool automatically generates an updated MEX function before running a test file. If the test file runs successfully, the simulation minimum and maximum values and the proposed types are displayed on the Variables tab. If you manually enter static ranges for a variable, the manually-entered ranges take precedence over the simulation ranges. If you manually modify the proposed types by typing or using the histogram, the data types are locked so that the tool cannot modify them. If the test file fails, the errors are displayed on the Simulation Output tab. Test files should exercise your algorithm over its full operating range. The quality of the proposed fixed-point data types depends on how well the test file covers the operating range of the algorithm with the desired accuracy. You can add test files and select to run more than one test file during the simulation. If you run multiple test files, the conversion tool merges the simulation results. Optionally, you can select to log data for histograms. After running a simulation, you can view the histogram for each variable. For more information, see “Histogram” on page 14-100. Computing Derived Ranges The advantage of proposing data types based on derived ranges is that you do not have to provide test files that exercise your algorithm over its full operating range. Running such test files often takes a very long time. To compute derived ranges and propose data types based on these ranges, provide static minimum and maximum values or proposed data types for all input variables. To improve the analysis, enter as much static range information as possible for other variables. You can manually enter ranges or promote simulation ranges to use as static ranges. Manually-entered static ranges always take precedence over simulation ranges. If you know what data type your hardware target uses, set the proposed data types to match this type. Manually-entered data types are locked so that the tool cannot modify 14-92 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion them. The tool uses these data types to calculate the input minimum and maximum values and to derive ranges for other variables. For more information, see “Locking Proposed Data Types” on page 14-93. When you select Compute Derived Ranges, the tool runs a derived range analysis to compute static ranges for variables in your MATLAB algorithm. When the analysis is complete, the static ranges are displayed on the Variables tab. If the run produces +/Inf derived ranges, consider defining ranges for all persistent variables. Optionally, you can select Quick derived range analysis. With this option, the conversion tool performs faster static analysis. The computed ranges might be larger than necessary. Select this option in cases where the static analysis takes more time than you can afford. If the derived range analysis for your project is taking a long time, you can optionally set a timeout. The tool aborts the analysis when the timeout is reached. Locking Proposed Data Types You can lock proposed data types against changes by the Fixed-Point Conversion tool using one of the following methods: • Manually setting a proposed data type in the Fixed-Point Conversion tool. • Right-clicking a type proposed by the tool and selecting Lock computed value. The tool displays locked data types in bold so that they are easy to identify. You can unlock a type using one of the following methods: • Manually overwriting it. • Right-clicking it and selecting Undo changes. This action unlocks only the selected type. • Right-clicking and selecting Undo changes for all variables. This action unlocks all locked proposed types. Viewing Functions You can view a list of functions in your project on the Navigation pane. This list also includes function specializations and class methods. When you select a function from the 14-93 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion list, the MATLAB code for that function or class method is displayed in the Fixed-Point Conversion tool code window. After conversion, the left pane also displays a list of output files including the fixedpoint version of the original algorithm. If your function is not specialized, the conversion retains the original function name in the fixed-point filename and appends the fixed-point suffix. For example, the fixed-point version of fun_with_matlab.m is fun_with_matlab_fixpt.m. Viewing Variables The Variables tab provides the following information for each variable in the function selected in the Navigation pane: • Type — The original data type of the variable in the MATLAB algorithm. • Sim Min and Sim Max — The minimum and maximum values assigned to the variable during simulation. You can edit the simulation minimum and maximum values. Edited fields are shown in bold. Editing these fields does not trigger static range analysis, but the tool uses the edited values in subsequent analyses. You can revert to the types proposed by the tool. • Static Min and Static Max — The static minimum and maximum values. To compute derived ranges and propose data types based on these ranges, provide static minimum and maximum values for all input variables. To improve the analysis, enter as much static range information as possible for other variables. When you compute derived ranges, the Fixed-Point Conversion tool runs a static analysis to compute static ranges for variables in your code. When the analysis is complete, the static ranges are displayed. You can edit the computed results. Edited fields are shown in bold. Editing these fields does not trigger static range analysis, but the tool uses the edited values in subsequent analyses. You can revert to the types proposed by the tool. 14-94 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion • Whole Number — Whether all values assigned to the variable during simulation are integers. The Fixed-Point Conversion tool determines whether a variable is always a whole number. You can modify this field. Edited fields are shown in bold. Editing these fields does not trigger static range analysis, but the tool uses the edited values in subsequent analyses. You can revert to the types proposed by the tool. • The proposed fixed-point data type for the specified word (or fraction) length. Proposed data types use the numerictype notation. For example, numerictype(1,16,12) denotes a signed fixed-point type with a word length of 16 and a fraction length of 12. numerictype(0,16,12) denotes an unsigned fixed-point type with a word length of 16 and a fraction length of 12. Because the tool does not apply data types to expressions, it does not display proposed types for them. Instead, it displays their original data types. You can also view and edit variable information in the code pane by placing your cursor over a variable name. You can use Ctrl+F to search for variables in the MATLAB code and on the Variables tab. The tool highlights occurrences in the code and displays only the variable with the specified name on the Variables tab. Viewing Information for MATLAB Classes The tool displays: • Code for MATLAB classes and code coverage for class methods in the code window. Use the Function list in the Navigation bar to select which class or class method to view. 14-95 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion • Information about MATLAB classes on the Variables tab. Specializations If a function is specialized, the tool lists each specialization and numbers them sequentially. For example, consider a function, dut, that calls subfunctions, foo and bar, multiple times with different input types. function y = dut(u, v) 14-96 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion tt1 = foo(u); tt2 = foo([u v]); tt3 = foo(complex(u,v)); ss1 = bar(u); ss2 = bar([u v]); ss3 = bar(complex(u,v)); y = (tt1 + ss1) + sum(tt2 + ss2) + real(tt3) + real(ss3); end function y = foo(u) y = u * 2; end function y = bar(u) y = u * 4; end 14-97 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion If you select a specialization, the app displays only the variables used by the specialization. 14-98 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion In the generated fixed-point code, the number of each fixed-point specialization matches the number in the Source Code list which makes it easy to trace between the floatingpoint and fixed-point versions of your code. For example, the generated fixed-point function for foo > 1 is named foo_s1. 14-99 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Histogram To log data for histograms, in the Fixed-Point Conversion window, click Run Simulation and select Log data for histogram, and then click the Run Simulation button. After simulation, to view the histogram for a variable, on the Variables tab, click the Proposed Type field for that variable. The histogram provides the range of the proposed data type and the percentage of simulation values that the proposed data type covers. The bit weights are displayed along 14-100 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion the X-axis, and the percentage of occurrences along the Y-axis. Each bin in the histogram corresponds to a bit in the binary word. For example, this histogram displays the range for a variable of type numerictype(1,16,14). You can view the effect of changing the proposed data types by: • Dragging the edges of the bounding box in the histogram window to change the proposed data type. 14-101 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion • Selecting or clearing Signed. To revert to the types proposed by the automatic conversion, in the histogram window, click . Function Replacements If your MATLAB code uses functions that do not have fixed-point support, the tool lists these functions on the Function Replacements tab. You can choose to replace unsupported functions with a custom function replacement or with a lookup table. You can add and remove function replacements from this list. If you enter a function replacements for a function, the replacement function is used when you build the 14-102 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion project. If you do not enter a replacement, the tool uses the type specified in the original MATLAB code for the function. Note: Using this table, you can replace the names of the functions but you cannot replace argument patterns. Validating Types Selecting Validate Types validates the build using the proposed fixed-point data types. If the validation is successful, you are ready to test the numerical behavior of the fixedpoint MATLAB algorithm. If the errors or warnings occur during validation, they are displayed on the Type Validation Output tab. If errors or warning occur: • On the Variables tab, inspect the proposed types and manually modified types to verify that they are valid. • On the Function Replacements tab, verify that you have provided function replacements for unsupported functions. Testing Numerics After validating the proposed fixed-point data types, select Test Numerics to verify the behavior of the fixed-point MATLAB algorithm. By default, if you added a test file to define inputs or run a simulation, the tool uses this test file to test numerics. Optionally, you can add test files and select to run more than one test file. The tool compares the numerical behavior of the generated fixed-point MATLAB code with the original floatingpoint MATLAB code. If you select to log inputs and outputs for comparison plots, the tool generates an additional plot for each scalar output. This plot shows the floating-point and fixed-point results and the difference between them. For non-scalar outputs, only the error information is shown. By default, the Fixed-Point Conversion tool runs the test files that you added and selected for running the simulation. You can add test files and select to run more than one test file to test numerics. If the numerical results do not meet your desired accuracy after fixed-point simulation, modify fixed-point data type settings and repeat the type validation and numerical 14-103 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion testing steps. You might have to iterate through these steps multiple times to achieve the desired results. Detecting Overflows When testing numerics, selecting Use scaled doubles to detect overflows enables overflow detection. When this option is selected, the conversion tool runs the simulation using scaled double versions of the proposed fixed-point types. Because scaled doubles store their data in double-precision floating-point, they carry out arithmetic in full range. They also retain their fixed-point settings, so they are able to report when a computation goes out of the range of the fixed-point type. . If the tool detects overflows, on its Overflow tab, it provides: • A list of variables and expressions that overflowed • Information on how much each variable overflowed • A link to the variables or expressions in the code window If your original algorithm uses scaled doubles, the tool also provides overflow information for these expressions. See Also “Detect Overflows” 14-104 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Instrumented MEX Functions Instrumented MEX Functions In this section... “Generating Instrumented MEX Functions” on page 14-105 “Merging Instrumentation Results” on page 14-105 “Clearing Instrumentation Results” on page 14-106 “Redirecting Entry-Point Calls to MEX Function” on page 14-106 “Proposing Fraction Lengths” on page 14-106 “Proposing Word Lengths” on page 14-106 Generating Instrumented MEX Functions Note: This capability is not compatible with automatic fixed-point conversion. If you select Convert to fixed point at build time, you cannot build instrumented MEX functions. Generating an instrumented MEX function for your MATLAB function enables instrumentation for logging minimum and maximum values of named and intermediate variables in your algorithm. It also enables instrumentation for log2 histograms of named, intermediate and expression values. When you run the instrumented MEX function, the instrumentation report provides fixed-point data type proposals based on the simulation range data. You can use this information to convert your MATLAB code to fixed point by hand. For more information, see “Propose Fixed-Point Data Types” on page 14-67 Merging Instrumentation Results When generating instrumented MEX functions, use the Merge instrumentation results from multiple simulations option to specify whether to merge new simulation minimum and maximum results with existing simulation results. Merging instrumentation results allows you to collect complete range information from multiple test files. 14-105 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Clearing Instrumentation Results When generating instrumented MEX functions, click the Clear instrumentation results button to clear instrumentation results from previous runs. Redirecting Entry-Point Calls to MEX Function By default, with the Redirect entry-point calls to MEX function option selected, the MATLAB Coder software automatically redirects calls to your MATLAB algorithm in the test file to calls to the generated MEX function. The generated MEX function must be in the same folder as the entry-point functions. If your test file already calls the MEX function, or you want to run the test file to test the original MATLAB algorithm, clear this option. Proposing Fraction Lengths When you simulate an instrumented MEX function, if you select to propose fraction lengths for the word lengths specified in the code, MATLAB Coder uses simulation minimum and maximum information and proposes fraction lengths for variables in your entry-point MATLAB function. For floating-point data types in your entry-point function, MATLAB Coder uses the word length and signedness specified in Default data type of all floating-point expressions to determine the optimal fraction lengths. Optionally, specify a safety margin to use when proposing fraction lengths. For more information, see “Modify Data Type Proposal Settings” on page 14-82. Proposing Word Lengths When you simulate an instrumented MEX function, if you select to propose word lengths for the fraction lengths specified in the code, MATLAB Coder uses simulation minimum and maximum information and proposes word lengths for variables in your entry-point MATLAB function. For floating-point data types in your entry-point function, MATLAB Coder uses the fraction length and signedness specified in Default data type of all floating-point expressions to determine the optimal word lengths. Optionally, specify a safety margin to use when proposing word lengths. For more information, see “Modify Data Type Proposal Settings” on page 14-82. 14-106 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Fixed-Point Conversion Project to MATLAB Scripts Convert Fixed-Point Conversion Project to MATLAB Scripts This example shows how to convert a MATLAB Coder project to MATLAB scripts when the project includes automated fixed-point conversion. You can use the -tocode option of the coder command to create a pair of scripts for fixed-point conversion and fixed-point code generation. You can use the scripts to repeat the project workflow in a commandline workflow. Before you convert the project to the scripts, you must complete the Test Numerics step of the fixed-point conversion process. Prerequisites This example uses the following files: • Project file fun_with_matlab.prj • Entry-point file fun_with_matlab.m • Test bench file fun_with_matlab_test.m • Generated fixed-point MATLAB file fun_with_matlab_fixpt.m To obtain these files, complete the example “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 14-4, including these steps: 1 Complete the Test Numerics step of the fixed-point conversion process. 2 Configure the project to build a C/C++ static library. Generate the Scripts 1 Change to the folder that contains the project file fun_with_matlab.prj and the entry-point function file fun_with_matlab.m. 2 At the command line, use the -tocode option of the coder command to convert the project to the scripts. Use the -script option to specify the file name for the scripts. coder -tocode fun_with_matlab_project -script fun_with_matlab_script.m The coder command generates two scripts in the current folder: fun_with_matlab_script.m contains the MATLAB commands to: • Create a code configuration object that has the same settings as the project. • Run the codegen command to convert the fixed-point MATLAB function fun_with_matlab_fixpt to a fixed-point C function. 14-107 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion fun_with_matlab_script_fixpt.m contains the MATLAB commands to: • Create a floating-point to fixed-point conversion configuration object that has the same fixed-point conversion settings as the project. • Run the codegen command to convert the MATLAB function fun_with_matlab to the fixed-point MATLAB function fun_with_matlab_fixpt. The suffix in the script file name is the generated fixed-point file name suffix specified by the project file. In this example, the suffix is the default value _fixpt. The coder command overwrites existing files that have the same names as the generated scripts. If you omit the -script option, the coder command writes the scripts to the Command Window. Run Script That Generates Fixed-Point C Code To run the script that generates fixed-point C code from fixed-point MATLAB code, the fixed-point MATLAB function specified in the script must be available. 1 Make sure that the fixed-point MATLAB function fun_with_matlab_fixpt.m is on the search path. addpath c:\coder\fun_with_matlab\codegen\fun_with_matlab\fixpt 2 Run the script: fun_with_matlab_script The code generation software generates a C static library with the name fun_with_matlab_fixpt in the folder codegen\lib \fun_with_matlab_fixpt. The variables cfg and ARGS appear in the base workspace. Run Script That Generates Fixed-Point MATLAB Code If you do not have the fixed-point MATLAB function, or if you want to regenerate it, use the script that generates the fixed-point MATLAB function from the floating-point MATLAB function. 1 Make sure that the current folder contains the entry-point function fun_with_matlab.m, and the test bench file fun_with_matlab_test.m. 14-108 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Fixed-Point Conversion Project to MATLAB Scripts 2 Run the script: fun_with_matlab_script_fixpt The code generation software generates fun_with_matlab_fixpt.m in the folder codegen\fun_with_matlab\fixpt. The variables cfg and ARGS appear in the base workspace. See Also coder.FixptConfig | codegen | coder Related Examples • “Convert MATLAB Code to Fixed-Point C Code” • “Propose Fixed-Point Data Types Based on Simulation Ranges” • “Convert MATLAB Coder Project to MATLAB Script” 14-109 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Generated Fixed-Point Code In this section... “Location of Generated Fixed-Point Files” on page 14-110 “Minimizing fi-casts to Improve Code Readability” on page 14-111 “Avoiding Overflows in the Generated Fixed-Point Code” on page 14-111 “Controlling Bit Growth” on page 14-112 “Avoiding Loss of Range or Precision” on page 14-112 “Handling Non-Constant mpower Exponents” on page 14-114 Location of Generated Fixed-Point Files By default, the fixed-point conversion process generates files in a folder named codegen/fcn_name/fixpt in your local working folder. fcn_name is the name of the MATLAB function that you are converting to fixed point. Filename Description fcn_name_fixpt.m Generated fixed-point MATLAB code. To integrate this fixed-point code into a larger application, consider generating a MEX-function for the function and calling this MEX-function in place of the original MATLAB code. fcn_name_fixpt_exVal.mat MAT-file containing: • A structure for the input arguments. • The name of the fixed-point file. fcn_name_fixpt_report.html Link to the type proposal report that displays the generated fixed-point code and the proposed type information. fcn_name_report.html Link to the type proposal report that displays the original MATLAB code and the proposed type information. 14-110 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generated Fixed-Point Code Filename Description fcn_name_wrapper_fixpt.m File that converts the floating-point data values supplied by the test file to the fixedpoint types determined for the inputs during the conversion step. These fixedpoint values are fed into the converted fixed-point function, fcn_name_fixpt. Minimizing fi-casts to Improve Code Readability The conversion process tries to reduce the number of fi-casts by analyzing the floatingpoint code. If an arithmetic operation is comprised of only compile-time constants, the conversion process does not cast the operands to fixed point individually. Instead, it casts the entire expression to fixed point. For example, here is the fixed-point code generated for the constant expression x = 1/ sqrt(2) when the selected word length is 14. Original MATLAB Code Generated Fixed-Point Code x = 1/sqrt(2); x = fi(1/sqrt(2), 0, 14, 14, fm); fm is the local fimath. Avoiding Overflows in the Generated Fixed-Point Code The conversion process avoids overflows by: • Using full-precision arithmetic unless you specify otherwise. • Avoiding arithmetic operations that involve double and fi data types. Otherwise, if the word length of the fi data type is not able to represent the value in the double constant expression, overflows occur. • Avoiding overflows when adding and subtracting non fixed-point variables and fixedpoint variables. The fixed-point conversion process casts non-fi expressions to the corresponding fi type. For example, consider the following MATLAB algorithm. 14-111 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion % A = 5; % B = ones(300, 1) function y = fi_plus_non_fi(A, B) % '1024' is non-fi, cast it y = A + 1024; % 'size(B, 1)*length(A)' is a non-fi, cast it y = A + size(B, 1)*length(A); end The generated fixed-point code is: %#codegen % A = 5; % B = ones(300, 1) function y = fi_plus_non_fi_fixpt(A, B) % '1024' is non-fi, cast it fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128,... 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi(A + fi(1024, 0, 11, 0, fm), 0, 11, 0, fm); % 'size(B, 1)*length(A)' is a non-fi, cast it y(:) = A + fi(size(B, fi(1, 0, 1, 0, fm))*length(A), 0, 9, 0, fm); end Controlling Bit Growth The conversion process controls bit growth by using subscripted assignments, that is, assignments that use the colon (:) operator, in the generated code. When you use subscripted assignments, MATLAB overwrites the value of the left-hand side argument but retains the existing data type and array size. Using subscripted assignment keeps fixed-point variables fixed point rather than inadvertently turning them into doubles. Maintaining the fixed-point type reduces the number of type declarations in the generated code. Subscripted assignment also prevents bit growth which is useful when you want to maintain a particular data type for the output. Avoiding Loss of Range or Precision Avoiding Loss of Range or Precision in Unsigned Subtraction Operations When the result of the subtraction is negative, the conversion process promotes the left operand to a signed type. 14-112 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generated Fixed-Point Code For example, consider the following MATLAB algorithm. % A = 1; % B = 5 function [y,z] = unsigned_subtraction(A,B) y = A - B; C = -20; z = C - B; end In the original code, both A and B are unsigned and the result of A-B can be negative. In the generated fixed-point code, A is promoted to signed. In the original code, C is signed, so does not require promotion in the generated code. %#codegen % A = 1; % B = 5 function [y,z] = unsigned_subtraction_fixpt(A,B) fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128,... 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi(fi_signed(A) - B, 1, 3, 0, fm); C = fi(-20, 1, 6, 0, fm); z = fi(C - B, 1, 6, 0, fm); end function y = fi_signed(a) coder.inline( 'always' ); if isfi( a ) && ~(issigned( a )) nt = numerictype( a ); new_nt = numerictype( 1, nt.WordLength + 1, nt.FractionLength ); y = fi( a, new_nt, fimath( a ) ); else y = a; end end Avoiding Loss of Range When Concatenating Arrays of Fixed-Point Numbers If you concatenate matrices using vertcat and horzcat, the conversion process uses the largest numerictype among the expressions of a row and casts the leftmost element to that type. This type is then used for the concatenated matrix to avoid loss of range. 14-113 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion For example, consider the following MATLAB algorithm. % A = 1, B = 100, C = 1000 function [y, z] = lb_node(A, B, C) %% single rows y = [A B C]; %% multiple rows z = [A 5; A B; A C]; end In the generated fixed-point code: • For the expression y = [A B C], the leftmost element, A, is cast to the type of C because C has the largest type in the row. • For the expression [A 5; A B; A C]: • In the first row, A is cast to the type of C because C has the largest type of the whole expression. • In the second row, A is cast to the type of B because B has the larger type in the row. • In the third row, A is cast to the type of C because C has the larger type in the row. %#codegen % A = 1, B = 100, C = 1000 function [y, z] = lb_node_fixpt(A, B, C) %% single rows fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128, ... 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi([fi(A, 0, 10, 0, fm) B C], 0, 10, 0, fm); %% multiple rows z = fi([fi(A, 0, 10, 0, fm) 5; fi(A, 0, 7, 0, fm) B;... fi(A, 0, 10, 0, fm) C], 0, 10, 0, fm); end Handling Non-Constant mpower Exponents If the function that you are converting has a scalar input, and the mpower exponent input is not constant, the conversion process sets the fimath ProductMode to 14-114 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generated Fixed-Point Code SpecifyPrecision in the generated code. With this setting , the output data type can be determined at compile time. For example, consider the following MATLAB algorithm. % a = 1 % b = 3 function y = exp_operator(a, b) % exponent is a constant so no need to specify precision y = a^3; % exponent is not a constant, use 'SpecifyPrecision' for 'ProductMode' y = b^a; end In the generated fixed-point code, for the expression y = a^3 , the exponent is a constant, so there is no need to specify precision. For the expression, y = b^a, the exponent is not constant, so the ProductMode is set to SpecifyPrecision. %#codegen % a = 1 % b = 3 function y = exp_operator_fixpt(a, b) % exponent is a constant so no need to specify precision fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128,... 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi(a^3, 0, 2, 0, fm); % exponent is not a constant, use 'SpecifyPrecision' for 'ProductMode' y(:) = fi(b, 'ProductMode', 'SpecifyPrecision',... 'ProductWordLength', 2, 'ProductFractionLength', 0 )^a; end 14-115 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Fixed-Point Code for MATLAB Classes In this section... “Automated Conversion Support for MATLAB Classes” on page 14-116 “Unsupported Constructs” on page 14-116 “Coding Style Best Practices” on page 14-117 Automated Conversion Support for MATLAB Classes The automated conversion process: • Proposes fixed-point data types based on simulation ranges for MATLAB classes. It does not propose data types based on derived ranges for MATLAB classes. After simulation, the Fixed-Point Conversion tool: • Function list contains class constructors, methods, and specializations. • Code window displays the objects used in each function. • Provides code coverage for methods. For more information, see “Viewing Information for MATLAB Classes”. • Supports class methods, properties, and specializations. For each specialization of a class, class_name, the conversion generates a separate class_name_fixpt.m file. For every instantiation of a class, the generated fixed-point code contains a call to the constructor of the appropriate specialization. • Supports classes that have get and set methods such as get.PropertyName, set.PropertyName. These methods are called when properties are read or assigned. The set methods can be specialized. Sometimes, in the generated fixed-point code, assignment statements are transformed to function calls. Unsupported Constructs The automated conversion process does not support: • Class inheritance. • Packages. • Constructors that use nargin and varargin. 14-116 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Code for MATLAB Classes Coding Style Best Practices When you write MATLAB code that uses MATLAB classes: • Initialize properties in the class constructor. • Replace constant properties with static methods. For example, consider the counter class. classdef Counter < handle properties Value = 0; end properties(Constant) MAX_VALUE = 128 end methods function out = next(this) out = this.Count; if this.Value == this.MAX_VALUE this.Value = 0; else this.Value = this.Value + 1; end end end end To use the automated fixed-point conversion process, rewrite the class to have a static class that initializes the constant property MAX_VALUE and a constructor that initializes the property Value. classdef Counter < handle properties Value; end methods(Static) function t = MAX_VALUE() t = 128; end end 14-117 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion methods function this = Counter() this.Value = 0; end function out = next(this) out = this.Value; if this.Value == this.MAX_VALUE this.Value = 0; else this.Value = this.Value + 1; end end end end 14-118 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion Best Practices Automated Fixed-Point Conversion Best Practices In this section... “Create a Test File” on page 14-119 “Prepare Your Algorithm for Code Acceleration or Code Generation” on page 14-120 “Check for Fixed-Point Support for Functions Used in Your Algorithm” on page 14-121 “Manage Data Types and Control Bit Growth” on page 14-121 “Convert to Fixed Point” on page 14-122 “Use the Histogram to Fine-Tune Data Type Settings” on page 14-122 “Optimize Your Algorithm” on page 14-124 “Avoid Explicit Double and Single Casts” on page 14-126 Create a Test File A best practice for structuring your code is to separate your core algorithm from other code that you use to test and verify the results. Create a test file to call your original MATLAB algorithm and fixed-point versions of the algorithm. For example, as shown in the following table, you might set up some input data to feed into your algorithm, and then, after you process that data, create some plots to verify the results. Since you need to convert only the algorithmic portion to fixed-point, it is more efficient to structure your code so that you have a test file, in which you create your inputs, call your algorithm, and plot the results, and one (or more) algorithmic files, in which you do the core processing. Original code Best Practice Modified code % TEST INPUT x = randn(100,1); Issue Test file Generation of test input and verification of results are intermingled with the algorithm code. % TEST INPUT x = randn(100,1); % ALGORITHM y = zeros(size(x)); y(1) = x(1); for n=2:length(x) y(n)=y(n-1) + x(n); end % VERIFY RESULTS yExpected=cumsum(x); Fix Create a test file that is separate from your algorithm. % ALGORITHM y = cumulative_sum(x); % VERIFY RESULTS yExpected = cumsum(x); plot(y-yExpected) title('Error') 14-119 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Original code plot(y-yExpected) title('Error') Best Practice Put the algorithm in its own function. Modified code Algorithm in its own function function y = cumulative_sum(x) y = zeros(size(x)); y(1) = x(1); for n=2:length(x) y(n) = y(n-1) + x(n); end end You can use the test file to: • Verify that your floating-point algorithm behaves as you expect before you convert it to fixed point. The floating-point algorithm behavior is the baseline against which you compare the behavior of the fixed-point versions of your algorithm. • Propose fixed-point data types. • Compare the behavior of the fixed-point versions of your algorithm to the floatingpoint baseline. • Help you determine initial values for static ranges. By default, the Fixed-Point Conversion tool shows code coverage results. Your test files should exercise the algorithm over its full operating range so that the simulation ranges are accurate. For example, for a filter, realistic inputs are impulses, sums of sinusoids, and chirp signals. With these inputs, using linear theory, you can verify that the outputs are correct. Signals that produce maximum output are useful for verifying that your system does not overflow. The quality of the proposed fixed-point data types depends on how well the test files cover the operating range of the algorithm with the accuracy that you want. Reviewing code coverage results help you verify that your test file is exercising the algorithm adequately. Review code flagged with a red code coverage bar because this code is not executed. If the code coverage is inadequate, modify the test file or add more test files to increase coverage. For more information see “Code Coverage”. Prepare Your Algorithm for Code Acceleration or Code Generation The automated conversion process instruments your code and provides data type proposals to help you convert your algorithm to fixed point. MATLAB algorithms that you want to convert to fixed point automatically must comply with code generation requirements and rules. To view the subset of the MATLAB 14-120 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion Best Practices language that is supported for code generation, see “Functions and Objects Supported for C and C++ Code Generation — Alphabetical List”. To help you identify unsupported functions or constructs in your MATLAB code, add the %#codegen pragma to the top of your MATLAB file. The MATLAB code analyzer flags functions and constructs that are not available in the subset of the MATLAB language supported for code generation. This advice appears in real-time as you edit your code in the MATLAB editor. For more information, see “Check Code With the Code Analyzer”. The software provides a link to a report that identifies calls to functions and the use of data types that are not supported for code generation. For more information, see “Check Code Using the Code Generation Readiness Tool”. Check for Fixed-Point Support for Functions Used in Your Algorithm The Fixed-Point Conversion tool flags unsupported function calls found in your algorithm on the Function Replacements tab. For example, if you use the fft, which is not supported for fixed point. The tool adds an entry to the table on this tab and indicates that you need to specify a replacement function to use for fixed-point operations. You can specify additional replacement functions. For example, functions like sin, cos, and sqrt may support fixed point, but for better efficiency, you may want to consider an alternative implementation like a lookup table or CORDIC-based algorithm. Manage Data Types and Control Bit Growth The automated fixed-point conversion process automatically manages data types and controls bit growth. It controls bit growth by using subscripted assignments, that is, assignments that use the colon (:) operator, in the generated code. When you use subscripted assignments, MATLAB overwrites the value of the left-hand side argument but retains the existing data type and array size. In addition to preventing bit growth, 14-121 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion subscripted assignment reduces the number of casts in the generated fixed-point code and makes the code more readable. Convert to Fixed Point What Are Your Goals for Converting to Fixed Point? Before you start the conversion, consider your goals for converting to fixed point. Are you implementing your algorithm in C or HDL? What are your target constraints? The answers to these questions determine many fixed-point properties such as the available word length, fraction length, and math modes, as well as available math libraries. To set up these properties, use the Advanced settings. For more information, see “Type Proposal Settings”. Run With Fixed-Point Types and Compare Results Create a test file to validate that the floating-point algorithm works as expected before converting it to fixed point. You can use the same test file to propose fixedpoint data types, and to compare fixed-point results to the floating-point baseline after the conversion. For more information, see “Running a Simulation” on page 14-91 and “Histogram” on page 14-100 . Use the Histogram to Fine-Tune Data Type Settings To fine-tune fixed-point type settings, use the histogram. To log data for histograms, in the Fixed-Point Conversion window, click Run Simulation and select Log data for histogram, and then click the Run Simulation button. 14-122 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion Best Practices After simulation and static analysis: • To view the histogram for a variable, on the Variables tab, click the Proposed Type field for that variable. 14-123 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion You can view the effect of changing the proposed data types by dragging the edges of the bounding box in the histogram window to change the proposed data type and selecting or clearing the Signed option. • If the values overflow and the range cannot fit the proposed type, the table shows proposed types in red. When the tool applies data types, it generates an html report that provides overflow information and highlights overflows in red. Review the proposed data types. Optimize Your Algorithm Use fimath to Get Optimal Types for C or HDL fimath properties define the rules for performing arithmetic operations on fi objects, including math, rounding, and overflow properties. You can use the fimath ProductMode and SumMode properties to retain optimal data types for C and HDL. HDL can have arbitrary word length types in the generated HDL code whereas C requires container types (uint8, uint16, uint32). Use the Advanced settings, see “Type Proposal Settings”. C The KeepLSB setting for ProductMode and SumMode models the behavior of integer operations in the C language, while KeepMSB models the behavior of many DSP devices. Different rounding methods require different amounts of overhead code. Setting the RoundingMethod property to Floor, which is equivalent to two's complement truncation, provides the most efficient rounding implementation. Similarly, the standard method for handling overflows is to wrap using modulo arithmetic. Other overflow handling methods create costly logic. Whenever possible, set OverflowAction to Wrap. MATLAB Code Best Practice Generated C Code Code being compiled Issue int adder(short a, short b) { int y; int i0; int i1; int i2; int i3; i0 = a; i1 = b; if ((i0 & 65536) != 0) { function y = adder(a,b) With the default word length set to y = a + b; 16 and the default fimath settings, end Note: In the Fixed-Point Conversion tool, set additional code is generated to implement saturation overflow, nearest rounding, and full-precision arithmetic. 14-124 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion Best Practices MATLAB Code Default word length to 16. Best Practice Generated C Code i2 = i0 | -65536; } else { i2 = i0 & 65535; } if ((i1 & 65536) != 0) { i3 = i1 | -65536; } else { i3 = i1 & 65535; } i0 = i2 + i3; if ((i0 & 65536) != 0) { y = i0 | -65536; } else { y = i0 & 65535; } return y; } Fix To make the generated C code more efficient, choose fixed-point math settings that match your processor types. int adder(short a, short b) { return a + b; } To customize fixed-point type proposals, use the Fixed-Point Conversion tool Advanced settings. Select fimath and then set: Rounding method Floor Overflow action Wrap Product mode KeepLSB Sum mode KeepLSB Product word length 32 Sum word length 32 14-125 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion HDL For HDL code generation, set: • ProductMode and SumMode to FullPrecision • Overflow action to Wrap • Rounding method to Floor Replace Built-in Functions With More Efficient Fixed-Point Implementations Some MATLAB built-in functions can be made more efficient for fixed-point implementation. For example, you can replace a built-in function with a Lookup table implementation, or a CORDIC implementation, which requires only iterative shift-add operations. For more information, see “Function Replacements” on page 14-102. Re-implement Division Operations Where Possible Often, division is not fully supported by hardware and can result in slow processing. When your algorithm requires a division, consider replacing it with one of the following options: • Use bit shifting when the denominator is a power of two. For example, bitsra(x,3) instead of x/8. • Multiply by the inverse when the denominator is constant. For example, x*0.2 instead of x/5. • If the divisor is not constant, use a temporary variable for the division. Doing so results in a more efficient data type proposal and, if overflows occur, makes it easier to see which expression is overflowing. Eliminate Floating-Point Variables For more efficient code, the automated fixed-point conversion process eliminates floatingpoint variables. The one exception to this is loop indices because they usually become integer types. It is good practice to inspect the fixed-point code after conversion to verify that there are no floating-point variables in the generated fixed-point code. Avoid Explicit Double and Single Casts For the automated workflow, do not use explicit double or single casts in your MATLAB algorithm to insulate functions that do not support fixed-point data types. The automated conversion tool does not support these casts. 14-126 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Automated Fixed-Point Conversion Best Practices Instead of using casts, supply a replacement function. For more information, see “Function Replacements” on page 14-102. 14-127 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Replacing Functions Using Lookup Table Approximations The Fixed-Point Designer software provides an option to generate lookup table approximations for continuous and stateless single-input, single-output functions in your original MATLAB code. These functions must be on the MATLAB path. You can use this capability to handle functions that are not supported for fixed point and to replace your own custom functions. The fixed-point conversion process infers the ranges for the function and then uses an interpolated lookup table to replace the function. You can control the interpolation method and number of points in the lookup table. By adjusting these settings, you can tune the behavior of replacement function to match the behavior of the original function as closely as possible. The fixed-point conversion process generates one lookup table approximation per call site of the function that needs replacement. To use lookup table approximations in a MATLAB Coder project, see “Replace the exp Function with a Lookup Table” and “Replace a Custom Function with a Lookup Table”. To use lookup table approximations in the programmatic workflow, see coder.approximation, “Replace the exp Function with a Lookup Table”, and “Replace a Custom Function with a Lookup Table”. 14-128 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان MATLAB Language Features Supported for Automated Fixed-Point Conversion MATLAB Language Features Supported for Automated Fixed-Point Conversion Fixed-Point Designer supports the following MATLAB language features in automated fixed-point conversion: • N-dimensional arrays • Matrix operations, including deletion of rows and columns • Variable-sized data (see “Generate Code for Variable-Size Data”). Range computation for variable–sized data is supported via simulation mode only. Variable-sized data is not supported for comparison plotting. • Subscripting (see “Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation”) • Complex numbers (see “Code Generation for Complex Data”) • Numeric classes (see “Supported Variable Types”) • Double-precision, single-precision, and integer math • Fixed-point arithmetic (see “Code Acceleration and Code Generation from MATLAB”) • Program control statements if, switch, for, while, and break • Arithmetic, relational, and logical operators • Local functions • Persistent variables (see “Define and Initialize Persistent Variables”) • Structures. Range computation for structures is supported via simulation mode only. • 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 convert your MATLAB algorithm to fixed point. • MATLAB classes. Range computation for MATLAB classes is supported via simulation mode only. Automated conversion supports: • Class properties 14-129 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion • Constructors • Methods • Specializations It does not support class inheritance or packages. For more information, see “FixedPoint Code for MATLAB Classes”. • Ability to call functions (see “Resolution of Function Calls for Code Generation” on page 13-2) • Subset of MATLAB toolbox functions (see “Functions Supported for Code Acceleration or C Code Generation”). • Subset of DSP System Toolbox System objects. The DSP System Toolbox System objects supported for automated conversion are: • dsp.BiquadFilter • dsp.FIRFilter, Direct Form only • dsp.FIRRateConverter • dsp.LowerTriangularSolver • dsp.UpperTriangularSolver • dsp.ArrayVectorAdder 14-130 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Inspecting Data Using the Simulation Data Inspector Inspecting Data Using the Simulation Data Inspector In this section... “What Is the Simulation Data Inspector?” on page 14-131 “Import Logged Data” on page 14-131 “Export Logged Data” on page 14-131 “Group Signals” on page 14-131 “Run Options” on page 14-132 “Create Report” on page 14-132 “Comparison Options” on page 14-132 “Enabling Plotting Using the Simulation Data Inspector” on page 14-132 “Save and Load Simulation Data Inspector Sessions” on page 14-132 What Is the Simulation Data Inspector? The Simulation Data Inspector allows you to view data logged during the fixed-point conversion process. You can use it to inspect and compare the inputs and outputs to the floating-point and fixed-point versions of your algorithm. For fixed-point conversion, there is no programmatic interface for the Simulation Data Inspector. Import Logged Data Before importing data into the Simulation Data Inspector, you must have previously logged data to the base workspace or to a MAT-file. Export Logged Data The Simulation Data Inspector provides the capability to save data collected by the fixedpoint conversion process to a MAT-file that you can later reload. The format of the MATfile is different from the format of a MAT-file created from the base workspace. Group Signals 14-131 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion You can customize the organization of your logged data in the Simulation Data Inspector Runs pane. By default, data is first organized by run. You can then organize your data by logged variable or no hierarchy. Run Options You can configure the Simulation Data Inspector to: • Append New Runs In the Run Options dialog box, the default is set to add new runs to the bottom of the run list. To append new runs to the top of the list, select Add new runs to top. • Specify a Run Naming Rule To specify run naming rules, in the Simulation Data Inspector toolbar, click Run Configuration. Create Report You can create a report of the runs or comparison plots. Specify the name and location of the report file. By default, the Simulation Data Inspector overwrites existing files. To preserve existing reports, select If report exists, increment file name to prevent overwriting. Comparison Options To change how signals are matched when runs are compared, specify the Align by and Then by parameters and then click OK. Enabling Plotting Using the Simulation Data Inspector To enable the Simulation Data Inspector in the Fixed-Point Conversion tool, see “Enable Plotting Using the Simulation Data Inspector”. To enable the Simulation Data Inspector in the programmatic workflow, see “Enable Plotting Using the Simulation Data Inspector”. Save and Load Simulation Data Inspector Sessions 14-132 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Inspecting Data Using the Simulation Data Inspector If you have data in the Simulation Data Inspector and you want to archive or share the data to view in the Simulation Data Inspector later, save the Simulation Data Inspector session. When you save a Simulation Data Inspector session, the MAT-file contains: • All runs, data, and properties from the Runs and Comparisons panes. • Check box selection state for data in the Runs pane. Save a Session to a MAT-File 1 On the Visualize tab, click Save. 2 Browse to where you want to save the MAT-file to, name the file, and click Save. Load a Saved Simulation Data Inspector Simulation 1 On the Visualize tab, click Open. 2 Browse, select the MAT-file saved from the Simulation Data Inspector, and click Open. 3 If data in the session is plotted on multiple subplots, on the Format tab, click Subplots and select the subplot layout. 14-133 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Custom Plot Functions The Fixed-Point Conversion tool provides a default time series based plotting function. The conversion process uses this function at the test numerics step to show the floatingpoint and fixed-point results and the difference between them. However, during fixedpoint conversion you might want to visualize the numerical differences in a view that is more suitable for your application domain. For example, plots that show eye diagrams and bit error differences are more suitable in the communications domain and histogram difference plots are more suitable in image processing designs. You can choose to use a custom plot function at the test numerics step. The Fixed-Point Conversion tool facilitates custom plotting by providing access to the raw logged input and output data before and after fixed-point conversion. You supply a custom plotting function to visualize the differences between the floating-point and fixed-point results. If you specify a custom plot function, the fixed-point conversion process calls the function for each input and output variable, passes in the name of the variable and the function that uses it, and the results of the floating-point and fixed-point simulations. Your function should accept three inputs: • A structure that holds the name of the variable and the function that uses it. Use this information to: • Customize plot headings and axes. • Choose which variables to plot. • Generate different error metrics for different output variables. • A cell array to hold the logged floating-point values for the variable. This cell array contains values observed during floating-point simulation of the algorithm during the test numerics phase. You might need to reformat this raw data. • A cell array to hold the logged values for the variable after fixed-point conversion. This cell array contains values observed during fixed-point simulation of the converted design. For example, function customComparisonPlot(varInfo, floatVarVals, fixedPtVarVals). To use a custom plot function, in the Fixed-Point Conversion tool, select Advanced, and then set Custom plot function to the name of your plot function. 14-134 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Custom Plot Functions In the programmatic workflow, set the coder.FixptConfig configuration object PlotFunction property to the name of your plot function. See “Visualize Differences Between Floating-Point and Fixed-Point Results”. 14-135 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Fixed-Point Conversion Data Type Issues in Generated Code Within the fixed-point conversion HTML report you have the option to highlight MATLAB code that results in double, single, or expensive fixed-point operations. Consider enabling these checks when trying to achieve a strict single, or fixed-point design. These checks are disabled by default. Enable the Highlight Option in a MATLAB Coder Project 1 2 Open the Settings menu. Under Plotting and Reporting, set Highlight potential data type issues to Yes. Enable the Highlight Option at the Command Line 1 Create a fixed-point code configuration object: cfg = coder.config('fixpt'); 2 Set the HighlightPotentialDataTypeIssues property of the configuration object to true. cfg.HighlightPotentialDataTypeIssues = true; Stowaway Doubles When trying to achieve a strict-single or fixed-point design, manual inspection of code can be time-consuming and error prone. This check highlights all expressions that result in a double operation. Stowaway Singles This check highlights all expressions that result in a single operation. Expensive Fixed-Point Operations The expensive fixed-point operations check identifies optimization opportunities by highlighting expressions in the MATLAB code which result in cumbersome 14-136 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Data Type Issues in Generated Code multiplication or division, or expensive rounding in generated code. For more information on optimizing generated fixed-point code, see “Tips for Making Generated Code More Efficient”. Cumbersome Operations Cumbersome operations most often occur due to insufficient range of output. Avoid inputs to a multiply or divide operation that have word lengths larger than the base integer type of your processor. Operations with larger word lengths can be handled in software, but this approach requires much more code and is much slower. Expensive Rounding Traditional handwritten code, especially for control applications, almost always uses "no effort" rounding. For example, for unsigned integers and two's complement signed integers, shifting right and dropping the bits is equivalent to rounding to floor. To get results comparable to, or better than, what you expect from traditional handwritten code, use the floor rounding method. This check identifies expensive rounding operations in multiplication and division. Expensive Comparison Operations Comparison operations generate extra code when a casting operation is required to do the comparison. For example, when comparing an unsigned integer to a signed integer, one of the inputs must first be cast to the signedness of the other before the comparison operation can be performed. Consider optimizing the data types of the input arguments so that a cast is not required in the generated code. 14-137 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-138 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow • “Convert MATLAB Code to Fixed-Point C Code” on page 15-2 • “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 15-5 • “Propose Fixed-Point Data Types Based on Derived Ranges” on page 15-11 • “Detect Overflows” on page 15-19 • “Replace the exp Function with a Lookup Table” on page 15-23 • “Replace a Custom Function with a Lookup Table” on page 15-25 • “Enable Plotting Using the Simulation Data Inspector” on page 15-28 • “Visualize Differences Between Floating-Point and Fixed-Point Results” on page 15-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Convert MATLAB Code to Fixed-Point C Code This example shows how to generate fixed-point C code from floating-point MATLAB code using the programmatic workflow. Set Up the Fixed-Point Configuration Object Create a fixed-point configuration object and configure the test file name. For example: fixptcfg = coder.config('fixpt'); fixptcfg.TestBenchName = 'fun_with_matlab_test'; Configure the Fixed-Point Configuration Object for Type Proposal The fixed-point conversion software can propose types based on simulation ranges, derived ranges, or both. • For type proposal using only simulation ranges, enable the collection and reporting of simulation range data. By default, derived range analysis is disabled. fixptcfg.ComputeSimulationRanges = true; • For type proposal using only derived ranges: 1 Specify the design range for input parameters. For example: fixptcfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0); 2 Enable derived range analysis. Disable collection and reporting of simulation range data. fixptcfg.ComputeDerivedRanges = true; fixptcfg.ComputeSimulationRanges = false; Enable Numerics Testing Select to run the test file to verify the generated fixed-point MATLAB code. fixptcfg.TestNumerics = true; Enable Plotting Log inputs and outputs for comparison plotting. Select to plot using a custom function or Simulation Data Inspector. For example, to plot using Simulation Data Inspector: fixptcfg.LogIOForComparisonPlotting = true; fixptcfg.PlotWithSimulationDataInspector = true; 15-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert MATLAB Code to Fixed-Point C Code Configure Additional Fixed-Point Configuration Object Properties Configure additional fixed-point configuration object properties as necessary. For example, define the default fixed-point word length: fixptcfg.DefaultWordLength = 16; Set Up the C Code Generation Configuration Object Create a code configuration object for generation of a C static library, dynamic library, or executable. Enable the code generation report. For example: cfg = coder.config('lib'); cfg.GenerateReport = true; Generate Fixed-Point C Code Use the codegen function to convert the floating-point MATLAB function to fixed-point C code. For example: codegen -float2fixed fixptcfg -config cfg fun_with_matlab View the Type Proposal Report Click the link to the type proposal report for the entry-point function. View the Comparison Plots If you selected to log inputs and outputs for comparison plots, the conversion process generates comparison plots. • If you selected to use Simulation Data Inspector for these plots, the Simulation Data Inspector opens. Use Simulation Data Inspector to view and compare the floatingpoint and fixed-point run information. • If you selected to use a custom plotting function for these plots, the conversion process uses the custom function to generate the plots. View the Generated Fixed-Point MATLAB and Fixed-Point C Code Click the View Report link that follows the type proposal report. To view the fixed-point MATLAB code, click the MATLAB code tab. To view the fixed-point C code, click the C code tab. See Also coder.FixptConfig 15-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Related Examples • “Propose Fixed-Point Data Types Based on Simulation Ranges” • “Propose Fixed-Point Data Types Based on Derived Ranges” • “Enable Plotting Using the Simulation Data Inspector” More About • “Automated Fixed-Point Conversion” 15-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Propose Fixed-Point Data Types Based on Simulation Ranges Propose Fixed-Point Data Types Based on Simulation Ranges This example shows how to propose fixed-point data types based on simulation range data. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/. You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a New Folder and Copy Relevant Files 1 Create a local working folder, for example, c:\fun_with_matlab. 2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB command line, enter: cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples')) 3 Copy the fun_with_matlab.m and fun_with_matlab_test.m files to your local working folder. Type Name Description Function code fun_with_matlab.m Entry-point MATLAB function Test file fun_with_matlab_test.m MATLAB script that tests fun_with_matlab.m The fun_with_matlab Function function y = fun_with_matlab(x) %#codegen 15-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow persistent z if isempty(z) z = zeros(2,1); end % [b,a] = butter(2, 0.25) b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175]; a = [1, -0.942809041582063, 0.3333333333333333]; y = zeros(size(x)); for i = 1:length(x) y(i) = b(1)*x(i) + z(1); z(1) = b(2)*x(i) + z(2) - a(2) * y(i); z(2) = b(3)*x(i) - a(3) * y(i); end end The fun_with_matlab_test Script The test script runs the fun_with_matlab function with three input signals: chirp, step, and impulse to cover the full intended operating range of the system. The script then plots the outputs. % fun_with_matlab_test % % Define representative inputs N = 256; % Number of points t = linspace(0,1,N); % Time vector from 0 to 1 second f1 = N/2; % Target frequency of chirp set to Nyquist x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second x_step = ones(1,N); % Step x_impulse = zeros(1,N); % Impulse x_impulse(1) = 1; % Run the function under test x = [x_chirp;x_step;x_impulse]; y = zeros(size(x)); for i = 1:size(x,1) y(i,:) = fun_with_matlab(x(i,:)); end % Plot the results titles = {'Chirp','Step','Impulse'} 15-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script clf for i = 1:size(x,1) subplot(size(x,1),1,i) plot(t,x(i,:),t,y(i,:)) title(titles{i}) legend('Input','Output') end xlabel('Time (s)') figure(gcf) disp('Test complete.') Set Up the Fixed-Point Configuration Object Create a fixed-point configuration object and configure the test file name. fixptcfg = coder.config('fixpt'); fixptcfg.TestBenchName = 'fun_with_matlab_test'; Set Up the C Code Generation Configuration Object Create a code configuration object to generate a C static library. Enable the code generation report. cfg = coder.config('lib'); cfg.GenerateReport = true; Collect Simulation Ranges and Generate Fixed-Point Code Use the codegen function to convert the floating-point MATLAB function, fun_with_matlab, to fixed-point C code. Set the default word length for the fixed-point data types to 16. fixptcfg.ComputeSimulationRanges = true; fixptcfg.DefaultWordLength = 16; % Derive ranges and generate fixed-point code codegen -float2fixed fixptcfg -config cfg fun_with_matlab codegen analyzes the floating-point code. Because you did not specify the input types for the fun_with_matlab function, the conversion process infers types by simulating the test file. The conversion process then derives ranges for variables in the algorithm. It uses these derived ranges to propose fixed-point types for these variables. When the conversion is complete, it generates a type proposal report. 15-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow View Range Information Click the link to the type proposal report for the fun_with_matlab function, fun_with_matlab_report.html. The report opens in a web browser. View Generated Fixed-Point MATLAB Code codegen generates a fixed-point version of the fun_with_matlab.m function, fun_with_matlab_fixpt.m, and a wrapper function that calls fun_with_matlab_fixpt. These files are generated in the codegen \fun_with_matlab\fixpt folder in your local working folder. function y = fun_with_matlab_fixpt(x) fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap', 'ProductMode',... 'FullPrecision', 'SumMode', 'FullPrecision'); %#codegen persistent z if isempty( z ) z = fi(zeros( 2, 1 ), 1, 16, 15, fm); end 15-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The fun_with_matlab_test Script % [b,a] = butter(2, 0.25) b = fi([ 0.0976310729378175, 0.195262145875635, 0.0976310729378175 ], 0, 16, 18, fm); a = fi([ 1, -0.942809041582063, 0.3333333333333333 ], 1, 16, 14, fm); y = fi(zeros( size( x ) ), 1, 16, 14, fm); for i = 1:length( x ) y( i ) = b( 1 )*x( i ) + z( 1 ); z( 1 ) = fi_signed(b( 2 )*x( i ) + z( 2 )) - a( 2 )*y( i ); z( 2 ) = fi_signed(b( 3 )*x( i )) - a( 3 )*y( i ); end end function y = fi_signed(a) coder.inline( 'always' ); if isfi( a ) && ~(issigned( a )) nt = numerictype( a ); new_nt = numerictype( 1, nt.WordLength + 1, nt.FractionLength ); y = fi( a, new_nt, fimath( a ) ); else y = a; end end View Generated Fixed-Point C Code To view the code generation report for the C code generation, click the View Report link that follows the type proposal report. The code generation report opens and displays the generated code for fun_with_matlab_fixpt.c. See Also coder.FixptConfig | codegen 15-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Related Examples • “Convert MATLAB Code to Fixed-Point C Code” • “Propose Fixed-Point Data Types Based on Derived Ranges” 15-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Propose Fixed-Point Data Types Based on Derived Ranges Propose Fixed-Point Data Types Based on Derived Ranges This example shows how to propose fixed-point data types based on static ranges that you specify. The advantage of proposing data types based on derived ranges is that you do not have to provide test files that exercise your algorithm over its full operating range. Running such test files often takes a very long time so you can save time by deriving ranges instead. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a New Folder and Copy Relevant Files 1 Create a local working folder, for example, c:\dti. 2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB command line, enter: cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples')) 3 Copy the dti.m and dti_test.m files to your local working folder. Type Name Description Function code dti.m Entry-point MATLAB function Test file dti_test.m MATLAB script that tests dti.m 15-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow The dti Function The dti function implements a Discrete Time Integrator in MATLAB. function [y, clip_status] = dti(u_in) %#codegen % Discrete Time Integrator in MATLAB % % Forward Euler method, also known as Forward Rectangular, or left-hand % approximation. The resulting expression for the output of the block at % step 'n' is y(n) = y(n-1) + K * u(n-1) % init_val = 1; gain_val = 1; limit_upper = 500; limit_lower = -500; % variable to hold state between consecutive calls to this block persistent u_state if isempty(u_state) u_state = init_val+1; end % Compute Output if (u_state > limit_upper) y = limit_upper; clip_status = -2; elseif (u_state >= limit_upper) y = limit_upper; clip_status = -1; elseif (u_state < limit_lower) y = limit_lower; clip_status = 2; elseif (u_state <= limit_lower) y = limit_lower; clip_status = 1; else y = u_state; clip_status = 0; end % Update State tprod = gain_val * u_in; u_state = y + tprod; 15-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function function b = subFunction(a) b = a*a; The dti_test Function The test script runs the dti function with a sine wave input. The script then plots the input and output signals. % dti_test % cleanup clear dti % input signal x_in = sin(2.*pi.*(0:0.001:2)).'; pause(10) len = length(x_in); y_out = zeros(1,len); is_clipped_out = zeros(1,len); for ii=1:len data = x_in(ii); % call to the dti function init_val = 0; gain_val = 1; upper_limit = 500; lower_limit = -500; % call to the design that does DTI [y_out(ii), is_clipped_out(ii)] = dti(data); end figure('Name', [mfilename, '_plot']) subplot(2,1,1) plot(1:len,x_in) xlabel('Time') ylabel('Amplitude') title('Input Signal (Sin)') subplot(2,1,2) plot(1:len,y_out) 15-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow xlabel('Time') ylabel('Amplitude') title('Output Signal (DTI)') disp('Test complete.') Set Up the Fixed-Point Configuration Object Create a fixed-point configuration object and configure the test file name. fixptcfg = coder.config('fixpt'); fixptcfg.TestBenchName = 'dti_test'; Specify Design Ranges Specify design range information for the dti function input parameter u_in. fixptcfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0) Enable Plotting Using the Simulation Data Inspector Select to run the test file to verify the generated fixed-point MATLAB code. Log inputs and outputs for comparison plotting and select to use the Simulation Data Inspector to plot the results. fixptcfg.TestNumerics = true; fixptcfg.LogIOForComparisonPlotting = true; fixptcfg.PlotWithSimulationDataInspector = true; Set Up the C Code Generation Configuration Object Create a code configuration object to generate a C static library. Enable the code generation report. cfg = coder.config('lib'); cfg.GenerateReport = true; Derive Ranges and Generate Fixed-Point Code Use the codegen function to convert the floating-point MATLAB function, dti, to fixedpoint C code. Set the default word length for the fixed-point data types to 16. fixptcfg.ComputeDerivedRanges = true; fixptcfg.ComputeSimulationRanges = false; fixptcfg.DefaultWordLength = 16; 15-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function % Derive ranges and generate fixed-point code codegen -float2fixed fixptcfg -config cfg dti codegen analyzes the floating-point code. Because you did not specify the input types for the dti function, the conversion process infers types by simulating the test file. The conversion process then derives ranges for variables in the algorithm. It uses these derived ranges to propose fixed-point types for these variables. When the conversion is complete, it generates a type proposal report. View Derived Range Information Click the link to the type proposal report for the dti function, dti_report.html. The report opens in a web browser. 15-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow View Generated Fixed-Point MATLAB Code codegen generates a fixed-point version of the dti function, dti_fxpt.m, and a wrapper function that calls dti_fxpt. These files are generated in the codegen\dti \fixpt folder in your local working folder. function [y,clip_status] = dti_fixpt(u_in) fm = fimath( 'RoundingMethod', 'Floor', 'OverflowAction', 'Wrap', 'ProductMode',... 'FullPrecision', 'MaxProductWordLength', 128, 'SumMode', 'FullPrecision',. 'MaxSumWordLength', 128); %#codegen % Discrete Time Integrator in MATLAB % % Forward Euler method, also known as Forward Rectangular, or left-hand % approximation. The resulting expression for the output of the block at % step 'n' is y(n) = y(n-1) + K * u(n-1) % init_val = fi(1, 0, 1, 0, fm); gain_val = fi(1, 0, 1, 0, fm); limit_upper = fi(500, 0, 9, 0, fm); limit_lower = fi(-500, 1, 10, 0, fm); % variable to hold state between consecutive calls to this block persistent u_state if isempty( u_state ) u_state = fi(init_val + fi(1, 0, 1, 0, fm), 1, 16, 6, fm); end % Compute Output if (u_state>limit_upper) y = fi(limit_upper, 1, 16, 6, fm); clip_status = fi(-2, 1, 16, 13, fm); elseif (u_state>=limit_upper) y = fi(limit_upper, 1, 16, 6, fm); clip_status = fi(-1, 1, 16, 13, fm); elseif (u_state Compare Floating-Point and Fixed-Point Runs Because you selected to log inputs and outputs for comparison plots and to use the Simulation Data Inspector for these plots, the Simulation Data Inspector opens. You can use the Simulation Data Inspector to view floating-point and fixed-point run information and compare results. For example, to compare the floating-point and fixed- 15-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The dti_test Function point values for the output y, on the Compare tab, select y, and then click Compare Runs. The Simulation Data Inspector displays a plot of the baseline floating-point run against the fixed-point run and the difference between them. View Generated Fixed-Point C Code To view the code generation report for the C code generation, click the View Report link that follows the type proposal report. 15-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow The code generation report opens and displays the generated code for dti_fixpt.c. See Also coder.FixptConfig | codegen Related Examples • “Convert MATLAB Code to Fixed-Point C Code” • “Propose Fixed-Point Data Types Based on Simulation Ranges” 15-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Detect Overflows Detect Overflows This example shows how to detect overflows at the command line. At the numerical testing stage in the conversion process, the tool simulates the fixed-point code using scaled doubles. It then reports which expressions in the generated code produce values that would overflow the fixed-point data type. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer In a local, writable folder, create a function, overflow. function y = overflow(b,x,reset) if nargin<3, reset = true; end persistent z p if isempty(z) || reset p = 0; z = zeros(size(b)); end [y,z,p] = fir_filter(b,x,z,p); end function [y,z,p] = fir_filter(b,x,z,p) y = zeros(size(x)); nx = length(x); nb = length(b); for n = 1:nx p=p+1; if p>nb, p=1; end z(p) = x(n); acc = 0; k = p; for j=1:nb acc = acc + b(j)*z(k); k=k-1; if k<1, k=nb; end end y(n) = acc; end end 15-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Create a test file, overflow_test.m to exercise the overflow algorithm. function overflow_test % The filter coefficients were computed using the FIR1 function from % Signal Processing Toolbox. % b = fir1(11,0.25); b = [-0.004465461051254 -0.004324228005260 +0.012676739550326 +0.074351188907780 +0.172173206073645 +0.249588554524763 +0.249588554524763 +0.172173206073645 +0.074351188907780 +0.012676739550326 -0.004324228005260 -0.004465461051254]'; % Input signal nx = 256; t = linspace(0,10*pi,nx)'; % Impulse x_impulse = zeros(nx,1); x_impulse(1) = 1; % Max Gain % The maximum gain of a filter will occur when the inputs line up with the % signs of the filter's impulse response. x_max_gain = sign(b)'; x_max_gain = repmat(x_max_gain,ceil(nx/length(b)),1); x_max_gain = x_max_gain(1:nx); % Sums of sines f0=0.1; f1=2; x_sines = sin(2*pi*t*f0) + 0.1*sin(2*pi*t*f1); % Chirp f_chirp = 1/16; x_chirp = sin(pi*f_chirp*t.^2); % Target frequency % Linear chirp x = [x_impulse, x_max_gain, x_sines, x_chirp]; titles = {'Impulse', 'Max gain', 'Sum of sines', 'Chirp'}; 15-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Detect Overflows y = zeros(size(x)); for i=1:size(x,2) reset = true; y(:,i) = overflow(b,x(:,i),reset); end test_plot(1,titles,t,x,y) end function test_plot(fig,titles,t,x,y1) figure(fig) clf sub_plot = 1; font_size = 10; for i=1:size(x,2) subplot(4,1,sub_plot) sub_plot = sub_plot+1; plot(t,x(:,i),'c',t,y1(:,i),'k') axis('tight') xlabel('t','FontSize',font_size); title(titles{i},'FontSize',font_size); ax = gca; ax.FontSize = 10; end figure(gcf) end Create a coder.FixptConfig object, fixptcfg, with default settings. fixptcfg = coder.config('fixpt'); Set the test bench name. In this example, the test bench function name is overflow_test. fixptcfg.TestBenchName = 'overflow_test'; Set the default word length to 16. fixptcfg.DefaultWordLength = 16; Enable overflow detection. fixptcfg.TestNumerics = true; fixptcfg.DetectFixptOverflows = true; 15-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Set the fimath Product mode and Sum mode to KeepLSB. These settings models the behavior of integer operations in the C language. fixptcfg.fimath = ... ['fimath(''RoundingMethod'',''Floor'',''OverflowAction'',' ... '''Wrap'',''ProductMode'',''KeepLSB'',''SumMode'',''KeepLSB'')']; Create a code generation configuration object to generate a standalone C static library. cfg = coder.config('lib'); Convert the floating-point MATLAB function, overflow, to fixed-point C code. You do not need to specify input types for the codegen command because it infers the types from the test file. codegen -float2fixed fixptcfg -config cfg overflow The numerics testing phase reports an overflow. Overflow error in expression 'acc + b( j )*z( k )'. Percentage of Current Range = 104%. Determine if the addition or the multiplication in this expression overflowed. Set the fimath ProductMode to FullPrecision so that the multiplication will not overflow, and then run the codegen command again. fixptcfg.fimath = ['fimath(''RoundingMethod'',''Floor'',''OverflowAction'',' ... '''Wrap'',''ProductMode'',''FullPrecision'',''SumMode'',''KeepLSB'')']; codegen -float2fixed fixptcfg -config cfg overflow The numerics testing phase still reports an overflow, indicating that it is the addition in the expression that is overflowing. 15-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace the exp Function with a Lookup Table Replace the exp Function with a Lookup Table This example shows how to replace the exp function with a lookup table approximation in the generated fixed-point code using the programmatic workflow. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB). For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ . You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create Algorithm and Test Files 1 Create a MATLAB function, my_fcn.m, that calls the exp function. function y = my_fcn(x) y = exp(x); end 2 Create a test file, my_fcn_test.m, that uses my_fcn.m. close all x = linspace(-10,10,1e3); for itr = 1e3:-1:1 y(itr) = my_fcn( x(itr) ); end plot( x, y ); Configure Approximation Create a function replacement configuration object to approximate the exp function, using the default settings of linear interpolation and 1000 points in the lookup table. q = coder.approximation('exp'); 15-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Set Up Configuration Object Create a coder.FixptConfig object, fixptcfg. Specify the test file name and enable numerics testing. Associate the function replacement configuration object with the fixedpoint configuration object. fixptcfg = coder.config('fixpt'); fixptcfg.TestBenchName = 'my_fcn_test'; fixptcfg.TestNumerics = true; fixptcfg.DefaultWordLength = 16; fixptcfg.addApproximation(q); Convert to Fixed Point Generate fixed-point MATLAB code. codegen -float2fixed fixptcfg my_fcn View Generated Fixed-Point Code To view the generated fixed-point code, click the link to my_fcn_fixpt. The generated code contains a lookup table approximation, exp1, for the exp function. The fixed-point conversion process infers the ranges for the function and then uses an interpolated lookup table to replace the function. By default, the lookup table uses linear interpolation, 1000 points, and the minimum and maximum values detected by running the test file. The generated fixed-point function, my_fcn_fixpt, calls this approximation instead of calling exp. function y = my_fcn_fixpt(x) fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128, ... 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi(exp1(x), 0, 16,1, fm); end You can now test the generated fixed-point code and compare the results against the original MATLAB function. If the behavior of the generated fixed-point code does not match the behavior of the original code closely enough, modify the interpolation method or number of points used in the lookup table and then regenerate code. 15-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace a Custom Function with a Lookup Table Replace a Custom Function with a Lookup Table This example shows how to replace a custom function with a lookup table approximation function using the programmatic workflow. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a MATLAB function, custom_fcn.m. This is the function that you want to replace. function y = custom_fcn(x) y = 1./(1+exp(-x)); end Create a wrapper function that calls custom_fcn.m. function y = call_custom_fcn(x) y = custom_fcn(x); end Create a test file, custom_test.m, that uses call_custom_fcn.m. close all x = linspace(-10,10,1e3); for itr = 1e3:-1:1 y(itr) = call_custom_fcn( x(itr) ); end plot( x, y ); 15-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Create a function replacement configuration object to approximate custom_fcn. Specify the function handle of the custom function and set the number of points to use in the lookup table to 50. q = coder.approximation('Function','custom_fcn',... 'CandidateFunction',@custom_fcn, 'NumberOfPoints',50); Create a coder.FixptConfig object, fixptcfg. Specify the test file name and enable numerics testing. Associate the function replacement configuration object with the fixedpoint configuration object. fixptcfg = coder.config('fixpt'); fixptcfg.TestBenchName = 'custom_test'; fixptcfg.TestNumerics = true; fixptcfg.addApproximation(q); Generate fixed-point MATLAB code. codegen -float2fixed fixptcfg call_custom_fcn codegen generates fixed-point MATLAB code in call_custom_fcn_fixpt.m. To view the generated fixed-point code, click the link to call_custom_fcn_fixpt. The generated code contains a lookup table approximation, custom_fcn1, for the custom_fcn function. The fixed-point conversion process infers the ranges for the function and then uses an interpolated lookup table to replace the function. The lookup table uses 50 points as specified. By default, it uses linear interpolation and the minimum and maximum values detected by running the test file. The generated fixed-point function, call_custom_fcn_fixpt, calls this approximation instead of calling custom_fcn. function y = call_custom_fcn_fixpt(x) fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',... 'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128, ... 'SumMode', 'FullPrecision', 'MaxSumWordLength', 128); y = fi(custom_fcn1(x), 0, 14, 14, fm); end You can now test the generated fixed-point code and compare the results against the original MATLAB function. If the behavior of the generated fixed-point code does not 15-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Replace a Custom Function with a Lookup Table match the behavior of the original code closely enough, modify the interpolation method or number of points used in the lookup table and then regenerate code. 15-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Enable Plotting Using the Simulation Data Inspector You can use the Simulation Data Inspector to inspect and compare floating-point and fixed-point logged input and output data. At the MATLAB command line: 1 Create a fixed-point configuration object and configure the test file name. fixptcfg = coder.config('fixpt'); fixptcfg.TestBenchName = 'dti_test'; 2 Select to run the test file to verify the generated fixed-point MATLAB code. Log inputs and outputs for comparison plotting and select to use the Simulation Data Inspector to plot the results. fixptcfg.TestNumerics = true; fixptcfg.LogIOForComparisonPlotting = true; fixptcfg.PlotWithSimulationDataInspector = true; 3 Generate fixed-point MATLAB code using codegen. codegen -float2fixed fixptcfg -config cfg dti For an example, see “Propose Fixed-Point Data Types Based on Derived Ranges”. 15-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualize Differences Between Floating-Point and Fixed-Point Results Visualize Differences Between Floating-Point and Fixed-Point Results This example shows how to configure the codegen function to use a custom plot function to compare the behavior of the generated fixed-point code against the behavior of the original floating-point MATLAB code. By default, when the LogIOForComparisonPlotting option is enabled, the conversion process uses a time series based plotting function to show the floating-point and fixedpoint results and the difference between them. However, during fixed-point conversion you might want to visualize the numerical differences in a view that is more suitable for your application domain. This example shows how to customize plotting and produce scatter plots at the test numerics step of the fixed-point conversion. Prerequisites To complete this example, you must install the following products: • MATLAB • MATLAB Coder • Fixed-Point Designer • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see http://www.mathworks.com/support/ compilers/current_release/ You can use mex -setup to change the default compiler. See “Changing Default Compiler”. Create a New Folder and Copy Relevant Files 1 Create a local working folder, for example, c:\custom_plot. 2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB command line, enter: cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples')) 3 Copy the myFilter.m, myFilterTest.m, plotDiff.m, and filterData.mat files to your local working folder. 15-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow Type Name Description Function code myFilter.m Entry-point MATLAB function Test file myFilterTest.m MATLAB script that tests myFilter.m Plotting function plotDiff.m Custom plot function MAT-fiile Data to filter. filterData.mat The myFilter Function function [y, ho] = myFilter(in) persistent b h; if isempty(b) b = complex(zeros(1,16)); h = complex(zeros(1,16)); h(8) = 1; end b = [in, b(1:end-1)]; y = b*h.'; errf = 1-sqrt(real(y)*real(y) + imag(y)*imag(y)); update = 0.001*conj(b)*y*errf; h = h + update; h(8) = 1; ho = h; end The myFilterTest File % load data data = load('filterData.mat'); d = data.symbols; for idx = 1:4000 y = myFilter(d(idx)); 15-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The plotDiff Function end The plotDiff Function % varInfo - structure with information about the variable. It has the following fields % i) name % ii) functionName % floatVals - cell array of logged original values for the 'varInfo.name' variable % fixedVals - cell array of logged values for the 'varInfo.name' variable after Fixed-P function plotDiff(varInfo, floatVals, fixedVals) varName = varInfo.name; fcnName = varInfo.functionName; % convert from cell to matrix floatVals = cell2mat(floatVals); fixedVals = cell2mat(fixedVals); % escape the '_'s because plot titles treat these as subscripts escapedVarName = regexprep(varName,'_','\\_'); escapedFcnName = regexprep(fcnName,'_','\\_'); % flatten the values flatFloatVals = floatVals(1:end); flatFixedVals = fixedVals(1:end); % build Titles floatTitle = [ escapedFcnName ' > ' 'float : ' escapedVarName ]; fixedTitle = [ escapedFcnName ' > ' 'fixed : ' escapedVarName ]; data = load('filterData.mat'); switch varName case 'y' x_vec = data.symbols; figure('Name', 'Comparison plot', 'NumberTitle', 'off'); % plot floating point values y_vec = flatFloatVals; subplot(1, 2, 1); plotScatter(x_vec, y_vec, 100, floatTitle); % plot fixed point values 15-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow y_vec = flatFixedVals; subplot(1, 2, 2); plotScatter(x_vec, y_vec, 100, fixedTitle); otherwise % Plot only output 'y' for this example, skip the rest end end function plotScatter(x_vec, y_vec, n, figTitle) % plot the last n samples x_plot = x_vec(end-n+1:end); y_plot = y_vec(end-n+1:end); hold on scatter(real(x_plot),imag(x_plot), 'bo'); hold on scatter(real(y_plot),imag(y_plot), 'rx'); title(figTitle); end Set Up Configuration Object 1 Create a coder.FixptConfig object. fxptcfg = coder.config('fixpt'); 2 Specify the test file name and custom plot function name. Enable logging and numerics testing. fxptcfg.TestBenchName = 'myFilterTest'; fxptcfg.PlotFunction = 'plotDiff'; fxptcfg.TestNumerics = true; fxptcfg. LogIOForComparisonPlotting = true; fxptcfg.DefaultWordLength = 16; Convert to Fixed Point Convert the floating-point MATLAB function, myFilter, to floating-point MATLAB code. You do not need to specify input types for the codegen command because it infers the types from the test file. codegen -args {complex(0, 0)} -float2fixed fxptcfg myFilter 15-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان The plotDiff Function The conversion process generates fixed-point code using a default word length of 16 and then runs a fixed-point simulation by running the myFilterTest.m function and calling the fixed-point version of myFilter.m. Because you selected to log inputs and outputs for comparison plots and to use the custom plotting function, plotDiff.m, for these plots, the conversion process uses this function to generate the comparison plot. 15-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 Automated Fixed-Point Conversion Using Programmatic Workflow The plot shows that the fixed-point results do not closely match the floating-point results. Increase the word length to 24 and then convert to fixed point again. fxptcfg.DefaultWordLength = 24; codegen -args {complex(0, 0)} -float2fixed fxptcfg myFilter The increased word length improved the results. This time, the plot shows that the fixedpoint results match the floating-point results. 15-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project • “MATLAB Coder Project Set Up Workflow” on page 16-2 • “Creating a New Project” on page 16-3 • “Opening an Existing Project” on page 16-5 • “Adding Files to the Project” on page 16-6 • “Specifying Properties of Primary Function Inputs in a Project” on page 16-7 • “Autodefine Input Types” on page 16-8 • “Define Input Parameters by Example in a Project” on page 16-12 • “Define or Edit Input Parameter Type in a Project” on page 16-19 • “Define Constant Input Parameters in a Project” on page 16-29 • “Define Inputs Programmatically in the MATLAB File” on page 16-30 • “Adding Global Variables in a Project” on page 16-31 • “Specifying Global Variable Type and Initial Value in a Project” on page 16-32 • “Specify Output File Name” on page 16-40 • “Specify Output File Locations” on page 16-41 • “Selecting Output Type” on page 16-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project MATLAB Coder Project Set Up Workflow 1 Create a new project or open an existing one. 2 Add the files from which you want to generate code. 3 Specify class, size, and complexity of all input parameters. 4 Optionally, add global variables. 5 Optionally, specify the output file name and output file locations. 6 Optionally, select the output type: MEX function (default), Instrumented MEX function, C/C++ static library, C/C++ dynamic library or C/C++ executable. 16-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Creating a New Project Creating a New Project From the MATLAB APPS Tab 1 Select the MATLAB Apps tab. 2 In the Code Generation group, click MATLAB Coder. 3 In the MATLAB Coder Project dialog box, on the New tab, enter the name of your project in the Name field. 4 Enter the location of the project in the Location field. Alternatively, use the ... (browse) button to navigate to the location. 5 Click OK. At the Command Line 1 At the MATLAB command line, enter: coder 2 In the Name field, enter the project_name. 3 In the Location field, enter the location of the project. 16-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Alternatively, use the ... (browse) button to navigate to the location. Note: The path should not contain spaces, as this can lead to code generation failures in certain operating system configurations. If the path contains non 7-bit ASCII characters, such as Japanese characters, MATLAB Coder might not be able to find files on this path. 4 Click OK. MATLAB Coder creates a project named project_name.prj in the specified location and marks it with the project icon: . From a MATLAB Coder Project If you already have a MATLAB Coder project open, in the upper-right corner of the project, click the Actions icon ( ) and select New Project. 16-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Opening an Existing Project Opening an Existing Project In this section... “From the MATLAB APPS Tab” on page 16-5 “At the Command Line” on page 16-5 “From a MATLAB Coder Project” on page 16-5 From the MATLAB APPS Tab 1 Select the MATLAB Apps tab. 2 In the Code Generation group, click MATLAB Coder. 3 In the MATLAB Coder Project dialog box, click the Open tab. 4 From the drop-down list, select a previously opened project or use the Browse button to find a project. 5 Click OK. At the Command Line 1 At the MATLAB command line, enter coder. 2 In the Code Generation Project dialog box, click the Open tab. 3 From the drop-down list, select a previously opened project or click the Browse button to find a project. 4 Click OK. From a MATLAB Coder Project If you already have a MATLAB Coder project open, in the upper-right corner of the project, click the Actions icon ( ) and select Open Project. 16-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Adding Files to the Project First, you must add the MATLAB files from which you want to generate code to the project. • Add only the main (entry-point) files that you call from MATLAB. • Do not add files that are called by these files. • Do not add files that have spaces in their names. The path should not contain spaces, as this can lead to code generation failures in certain operating system configurations. • If the path contains non 7-bit ASCII characters, such as Japanese characters, MATLAB Coder might not be able to find files on this path. To add a file, do one of the following: • In the project, in the Entry-Point Files pane on the Overview tab, click the Add files link and browse to the file. • Drag a file from the current folder and drop it in the Entry-Point Files pane on the Overview tab. If you add more than one entry-point file, MATLAB Coder lists them alphabetically. If the functions that you added have inputs, you must define these inputs. See “Specifying Properties of Primary Function Inputs in a Project” on page 16-7. 16-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying Properties of Primary Function Inputs in a Project Specifying Properties of Primary Function Inputs in a Project Why You Must Specify Input Properties Because C and C++ are statically typed languages, MATLAB Coder must determine the properties of all variables in the MATLAB files at code generation time. To infer variable properties in MATLAB files, MATLAB Coder must be able to identify the properties of the inputs to the entry-point function. Therefore, if your entry-point function has inputs, you must specify the properties of these inputs. If your primary function has no input parameters, MATLAB Coder can compile your MATLAB file without modification. You do not need to specify properties of inputs to local functions or external functions called by the entry-point function. You must specify the same number and order of inputs as the MATLAB function unless you use the tilde (~) character to specify unused function inputs. If you use the tilde character, the inputs default to real, scalar doubles. See Also • “Properties to Specify” How to Specify an Input Definition in a Project Specify an input definition in your MATLAB Coder project using one of the following methods: • Autodefine Input Types • Define Type • Define by Example • Define Constant • Define Programmatically in the MATLAB File Alternatively, specify input definitions at the command line and then use the codegen function to generate code. For more information, see “Primary Function Input Specification” on page 19-39. 16-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Autodefine Input Types In this section... “How MATLAB Coder Autodefines Input Types” on page 16-8 “Prerequisites for Autodefining Input Types” on page 16-8 “How to Autodefine Input Types” on page 16-8 How MATLAB Coder Autodefines Input Types If you specify a test file that calls the project entry-point functions, the MATLAB Coder software can infer the input parameter types by running the test file. If a test file calls an entry-point function multiple times with different sized inputs, the MATLAB Coder software takes the union of the inputs and infers that the inputs are variable size, with an upper bound equal to the size of the largest input. Prerequisites for Autodefining Input Types Before using MATLAB Coder to autodefine function input parameter types, you must add at least one entry-point file to your project. You must also specify a test file that calls your entry-point functions with the expected input types. The test file can be either a MATLAB function or a script. It should call the entry-point function at least once. How to Autodefine Input Types 1 On the MATLAB Coder project Overview tab, click the Autodefine types link. 16-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Autodefine Input Types 2 In the Autodefine Input Types dialog box, click the the project. 3 Browse to the folder that contains the test file and select the file. button to add a test file to Alternatively, if you have already added test files to the project, select one from the list. 4 Click the Run button. The software runs the test file and, if the file calls entry-point functions, infers input types for these functions. 16-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project The dialog box displays a summary of the inferred types and provides the following options: • Make dimensions variable-sized if they are at least If you want inputs above a specified size to be variable size with an upper bound, select this option and specify the threshold. If the size, S, of any dimension of an input is equal to or greater than this threshold, the software makes this dimension variable size with an upper bound of S. • Make dimensions unbounded if they are at least If you want inputs above a specified size to be variable size with no upper bounds (unbounded), select this option and specify the threshold. If the size of any dimension of an input is equal to or greater than this threshold, the software makes this dimension unbounded. 16-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Autodefine Input Types 5 Review the inferred types. If the types are acceptable, click Use These Types. Otherwise, modify your test file, use a different test file to autodefine the types or define them using an alternate method. For more information, see “How to Specify an Input Definition in a Project” on page 16-7. 16-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Define Input Parameters by Example in a Project In this section... “How to Define an Input Parameter by Example” on page 16-12 “Specifying Input Parameters by Example” on page 16-13 “Specifying an Enumerated Type Input Parameter by Example” on page 16-15 “Specifying a Fixed-Point Input Parameter by Example” on page 16-16 How to Define an Input Parameter by Example 1 On the MATLAB Coder project Overview tab, click the input parameter that you want to define. 16-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Parameters by Example in a Project 2 From the list of input options, select Define by Example. 3 In the field to the right of the parameter, enter a MATLAB expression. MATLAB Coder software uses the class, size, and complexity of the value of the specified variable or MATLAB expression when compiling the code. Specifying Input Parameters by Example This example shows how too specify a 1-by-4 vector of unsigned 16-bit integers. 1 On the MATLAB Coder project Overview tab, click the input parameter that you want to define. 16-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project 2 From the list of input options, select Define by Example. 3 In the field to the right of the parameter, enter: zeros(1,4,'uint16') The input type is uint16(1x4). 4 Optionally, after specifying the input type, you can specify that the input is variable size. Select the second dimension. 16-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Parameters by Example in a Project 5 From the list of size options, select :4 to specify that the second dimension is variable size with an upper bound of 4. Alternatively, select :Inf to specify that the second dimension is unbounded. Alternatively, you can specify that the input is variable size by using the coder.newtype function. Enter the following MATLAB expression: coder.newtype('uint16',[1 4],[0 1]) Note: To specify that an input is a double-precision scalar, simply enter 0. Specifying an Enumerated Type Input Parameter by Example This example shows how to specify that an input uses the enumerated type MyColors. 1 Define an enumeration MyColors. On the MATLAB path, create a file named 'MyColors' containing: classdef(Enumeration) MyColors < int32 enumeration green(1), red(2), end 16-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project end 2 On the MATLAB Coder project Overview tab, click to the input parameter that you want to define. 3 From the list of input options, select Define by Example. 4 In the field to the right of the parameter, enter the following MATLAB expression: MyColors.red Specifying a Fixed-Point Input Parameter by Example To specify fixed-point inputs, you must install Fixed-Point Designer software. 16-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Parameters by Example in a Project This example shows how to specify a signed fixed-point type with a word length of 8 bits, and a fraction length of 3 bits. 1 On the MATLAB Coder project Overview tab, click the input parameter that you want to define. 2 From the list of input options, select Define by Example. 3 In the field to the right of the parameter, enter: fi(10, 1, 8, 3) 16-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project MATLAB Coder sets the type of input u to embedded.fi(1x1). By default, if you have not specified a local fimath, MATLAB Coder uses the default fimath. For more information, see “fimath for Sharing Arithmetic Rules”. Optionally, modify the fixed-point properties of the input, see “Specifying a FixedPoint Input Parameter by Type” on page 16-22 or the size of the input, see “Define or Edit Input Parameter Type in a Project” on page 16-19. 16-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define or Edit Input Parameter Type in a Project Define or Edit Input Parameter Type in a Project In this section... “How to Define or Edit an Input Parameter Type” on page 16-19 “Specifying an Enumerated Type Input Parameter by Type” on page 16-21 “Specifying a Fixed-Point Input Parameter by Type” on page 16-22 “Specifying Structures” on page 16-23 How to Define or Edit an Input Parameter Type The following procedure is for input types double, single, int64, int32, int16, int8, uint64, uint32, uint16, uint8, logical, and char. For more information about defining other types, see the following table. Input Type Link A structure (struct) “Specifying Structures” on page 16-23 A fixed-point data type (embedded.fi) “Specifying a Fixed-Point Input Parameter by Type” on page 16-22 An input by example (Define by Example) “Define Input Parameters by Example in a Project” on page 16-12 A constant (Define Constant) “Define Constant Input Parameters in a Project” on page 16-29 1 On the Overview tab Entry-Point Files pane, click the field to the right of the input parameter name to view the input options. 16-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project 2 Optionally, for numeric types, select Complex number to make the parameter a complex type. By default, inputs are real. 3 Select the input type. The selected type is displayed for the input parameter together with size options. 16-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define or Edit Input Parameter Type in a Project 4 From the list, select whether your input is a scalar, a 1 x n vector, a m x 1 vector or a m x n matrix. By default, if you do not select a size option, MATLAB Coder defines inputs as scalars. 5 Optionally, if your input is not scalar, enter sizes m and n. You can specify: • Fixed size, for example, 10. • Variable size, up to a specified limit, by using the : prefix. For example, to specify that your input can vary in size up to 10, enter :10. • Unbounded variable size by entering :Inf. You can edit the size of each dimension after specifying it. Specifying an Enumerated Type Input Parameter by Type To specify that an input uses the enumerated type MyColors: 1 Define an enumeration MyColors. On the MATLAB path, create a file named 'MyColors' containing: 16-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project classdef(Enumeration) MyColors < int32 enumeration green(1), red(2), end end 2 In the field to the right of the input parameter, enter MyColors. Specifying a Fixed-Point Input Parameter by Type To specify fixed-point inputs, you must install Fixed-Point Designer software. 1 On the Overview tab Entry-Point Files pane, click the box to the right of the input parameter name to view the input options. 2 Select embedded.fi. The Properties dialog box opens. 16-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define or Edit Input Parameter Type in a Project 3 In this dialog box, set up the input parameter numerictype and fimath properties and then close the dialog box. If you do not specify a local fimath, MATLAB Coder uses the default fimath. For more information, see “Default fimath Usage to Share Arithmetic Rules”. 4 The size of the input defaults to 1x1. Optionally, modify the size by selecting the dimension that you want to change and entering a new size. Specifying Structures When a primary input is a structure, MATLAB Coder treats each field as a separate input. Therefore, you must specify properties for all fields of a primary structure input in the order that they appear in the structure definition, as follows: • For each field of input structures, specify class, size, and complexity. • For each field that is fixed-point class, also specify numerictype, and fimath. Specifying Structures by Type 1 On the Overview tab Entry-Point Files pane, click the field to the right of the input parameter name to view the input options. 16-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project 2 From the list of input options, select struct. The selected type, struct, is displayed for the input parameter together with size options. 16-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define or Edit Input Parameter Type in a Project 3 From the list, select whether your structure is a scalar, 1 x n vector, m x 1 vector or m x n matrix. By default, if you do not select a size option, MATLAB Coder defines inputs as scalars. 4 Optionally, if your input is not scalar, enter sizes m and n. You can specify: • Fixed size, for example, 10. • Variable size, up to a specified limit, by using the : prefix. For example, to specify that your input can vary in size up to 10, enter :10. • Unbounded variable size by entering :Inf. 5 Optionally, add fields to the structure as described in “How to Add a Field to a Structure” on page 16-28 and then set their size and complexity. 6 Optionally, specify properties for the structure in the generated code as described in “How to Set Structure Properties” on page 16-25. How to Set Structure Properties 1 To the right of the structure definition, click the Actions icon, ( ). 16-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project The structure properties dialog box opens. 2 Specify properties for the structure in the generated code. Property Description C type definition name Name to use for the structure variable in the generated code. Type definition is externally defined Default: No — type definition is not externally defined If you select ‘Yes’ to declare an externally defined structure, MATLAB Coder does not generate the definition of the structure type; you must provide it in a custom include file. Dependency: This option is enabled by C type definition name. C type definition header file Name of the header file that contains the external definition of the structure, for example, "mystruct.h". Specify the path to the file using the Additional include directories parameter on the Project Settings dialog box Custom Code tab. 16-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define or Edit Input Parameter Type in a Project Property Description By default, the generated code contains #include statements for custom header files after the standard header files. If a standard header file refers to the custom structure type, then the compilation fails. By specifying the C type definition header file option, MATLAB Coder includes that header file exactly at the point where it is required. Must be a non-empty string. Dependency: This option is enabled when Type definition is externally defined is set to Yes. Data alignment boundary The run-time memory alignment of structures of this type in bytes. If you have an Embedded Coder license and use Code Replacement Libraries (CRLs), the CRLs provide the ability to align data objects passed into a replacement function to a specified boundary. This capability allows you to take advantage of target-specific function implementations that require data to be aligned. By default, the structure is not aligned on any specific boundary so it will not be matched by CRL functions that require alignment. Alignment must be either -1 or a power of 2 that is no more than 128. Default: 0 Dependency: This option is enabled when Type definition is externally defined is set to Yes. 16-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project How to Rename a Field in a Structure On the project Overview tab, select the name field of the structure that you want to rename and enter the new name. How to Add a Field to a Structure 1 On the project Overview tab, select the structure to which you want to add a field. 2 To the right of the structure, click the Actions icon ( ) to open the context menu. 3 From the menu, select Add Field. If the structure already contains other fields, MATLAB Coder adds the field after the existing fields. 4 Enter the field name and define its type. How to Insert a Field into a Structure 1 On the project Overview tab, select the field under which you want to add another field. 2 To the right of the structure, click the Actions icon ( ) to open the context menu. 3 From the menu, select Insert Field. MATLAB Coder adds the field after the selected field. 4 Enter the field name and define its type. How to Remove a Field from a Structure 1 In the project Overview tab, select the field that you want to remove. 2 To the right of the structure, click the Actions icon ( ) to open the context menu. 3 From the menu, select Remove Field. 16-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Constant Input Parameters in a Project Define Constant Input Parameters in a Project 1 On the Overview tab Entry-Point Files pane, click the field to the right of the input parameter name to view the input options. 2 Select Define Constant. 3 In the field to the right of the parameter name, enter the value of the constant or a MATLAB expression that represents the constant. MATLAB Coder software uses the value of the specified MATLAB expression as a compile-time constant. 16-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Define Inputs Programmatically in the MATLAB File You can use the MATLAB assert function to define properties of primary function inputs directly in your MATLAB entry-point files. To enable this option, on the Project Settings dialog box All Settings tab, under Advanced, select Determine input types from source code preconditions. If you enable this option: • MATLAB Coder labels all entry-point function inputs as Deferred and determines the input types at compile time. • You cannot specify input types in this project using any other input specification method. For more information, see “Define Input Properties Programmatically in the MATLAB File”. 16-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adding Global Variables in a Project Adding Global Variables in a Project To add global variables to the project: 1 On the project Overview tab, click Add global. By default, MATLAB Coder names the first global variable in a project g, and subsequent global variables g1, g2, etc. 2 Enter the name of the global variable. 3 After adding a global variable, before building the project, specify its type and initial value. If you do not do this, you must create a variable with the same name in the global workspace. See “Specifying Global Variable Type and Initial Value in a Project” on page 16-32. 16-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Specifying Global Variable Type and Initial Value in a Project In this section... “Why Specify a Type Definition for Global Variables?” on page 16-32 “How to Specify a Global Variable Type” on page 16-32 “Defining a Global Variable by Example” on page 16-33 “Defining or Editing Global Variable Type” on page 16-34 “Defining Global Variable Initial Value” on page 16-36 “Defining Global Variable Constant Value” on page 16-38 “Removing Global Variables” on page 16-39 Why Specify a Type Definition for Global Variables? If you use global variables in your MATLAB algorithm, before building the project, you must add a global type definition and initial value for each. If you do not initialize the global data, MATLAB Coder looks for the variable in the MATLAB global workspace. If the variable does not exist, MATLAB Coder generates an error. C and C++ use static typing. To determine the types of your variables before use, MATLAB Coder requires a complete assignment to each variable. At code generation time, MATLAB Coder needs to have an initial value to determine the type of a global variable. Otherwise, the global variable might be used before it is defined and then MATLAB Coder cannot determine the type to use in the generated code. For MEX functions, if you use global data, you must also specify whether to synchronize this data between MATLAB and the MEX function. For more information, see “Synchronizing Global Data with MATLAB”. How to Specify a Global Variable Type 1 Specify the type of each global variable using one of the following methods: • Define by example • Define type 2 Define an initial value for each global variable. 16-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying Global Variable Type and Initial Value in a Project If you do not provide a type definition and initial value for a global variable, you must create a variable with the same name and suitable class, size, complexity, and value in the MATLAB workspace. Defining a Global Variable by Example 1 On the project Overview tab, click the field to the right of the global variable that you want to define. 2 Select Define by Example. 3 In the field to the right of the global name, enter a MATLAB expression that has the required class, size, and complexity. MATLAB Coder software uses the class, size, and complexity of the value of this expression as the type for the global variable. 4 Optionally, change the size of the global variable. Click the dimension that you want to change and enter the size, for example, 10. 16-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project You can specify: • Fixed size. In this example, select 10. • Variable size, up to a specified limit, by using the : prefix. In this example, to specify that your input can vary in size up to 10, select :10. • Unbounded variable size by selecting :Inf. Note: You define global variables in the same way that you define input parameters. For more information, see “Define Input Parameters by Example in a Project” on page 16-12 Defining or Editing Global Variable Type 1 On the project Overview tab, click the field to the right of the global variable that you want to define. 16-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying Global Variable Type and Initial Value in a Project 2 Optionally, for numeric types, select Complex to make the parameter a complex type. By default, inputs are real. 3 Select the type for the global variable. For example, double. By default, the global variable is a scalar. 4 Optionally, change the size of the global variable. Click the dimension that you want to change and enter the size, for example, 10. You can specify: 16-35 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project • Fixed size. In this example, select 10. • Variable size, up to a specified limit, by using the : prefix. In this example, to specify that your input can vary in size up to 10, select :10. • Unbounded variable size by selecting :Inf. Defining Global Variable Initial Value • “Define Initial Value Before Defining Type” on page 16-36 • “Define Initial Value After Defining Type” on page 16-37 Define Initial Value Before Defining Type 1 On the project Overview tab, click the field to the right of the global variable. 2 Select Define Initial Value. 3 Enter a MATLAB expression. MATLAB Coder software uses the value of the specified MATLAB expression as the value of the global variable. Because you 16-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying Global Variable Type and Initial Value in a Project did not define the type of the global variable before you defined its initial value, MATLAB Coder uses the type of the initial value as the global variable type. The project displays that the global variable is initialized. If you change the type of a global variable after defining its initial value, you must redefine the initial value. Define Initial Value After Defining Type 1 On the project Overview tab, click the type field of the global variable. 2 Select Define Initial Value. 16-37 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project 3 Enter a MATLAB expression. MATLAB Coder software uses the value of the specified MATLAB expression as the value of the global variable. The project displays that the global variable is initialized. Defining Global Variable Constant Value 1 On the project Overview tab, click the field to the right of the global variable. 2 3 Select Define Constant Value. In the field to the right of the global variable, enter a MATLAB expression. 16-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specifying Global Variable Type and Initial Value in a Project Removing Global Variables 1 On the project Overview tab, select the global variable that you want to remove. 2 To the right of the variable, click the Actions icon ( 3 From this menu, select Remove Global. ) to open the context menu. MATLAB Coder removes the global variable. 16-39 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Specify Output File Name On the project Build tab, in the Output file field, enter the file name. The file name can include an existing path. Note: Do not put any spaces in the file name. By default, if the name of the first entry-point MATLAB file is fcn1, the output file name is: • fcn1 for C/C++ libraries and executables. • fcn1_mex for MEX functions. By default, MATLAB Coder generates files in the folder project_folder/codegen/ target/fcn1: • project_folder is your current project folder • target is: • mex for MEX functions • lib for static C/C++ libraries • dll for dynamic C/C++ libraries • exe for C/C++ executables To learn how to change the default output folder, see “Specify Output File Locations” on page 16-41. Command Line Alternative Use the codegen function -o option. 16-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Output File Locations Specify Output File Locations The path should not contain: • Spaces, as this can lead to code generation failures in certain operating system configurations. • Non 7-bit ASCII characters, such as Japanese characters. 1 On the project Build tab, click More settings. 2 In the Project Settings dialog box, click the Paths tab. The default setting for the Build Folder field is A subfolder of the project folder. By default, MATLAB Coder generates files in the folder project_folder/ codegen/target/fcn1: • fcn1 is the name of the first entry-point file • target is: • mex for MEX functions • dll for dynamic C/C++ libraries • lib for static C/C++ libraries • exe for C/C++ executables 3 To change the output location, you can either: • Set Build Folder to A subfolder of the current MATLAB working folder MATLAB Coder generates files in the MATLAB_working_folder/codegen/ target/fcn1 folder • Set Build Folder to Specified folder. In the Build folder name field, provide the path to the folder. Command Line Alternative Use the codegen function -d option. 16-41 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project Selecting Output Type On the project Build tab, from the Output type drop-down list, select one of the available output types: • MEX Function (default) • Instrumented MEX Function Building an instrumented MEX function requires a Fixed-Point Designer license and clears prior instrumentation results. • C/C++ Static Library • C/C++ Dynamic Library • C/C++ Executable Command Line Alternative Use the codegen function -config option. Changing Output Type MEX functions use a different set of configuration parameters than C/C++ libraries and executables use. When you switch the output type between MEX Function or Instrumented MEX Function and C/C++ Static Library, C/C++ Dynamic Library or C/C++ Executable, you should verify these settings. If you enable any of the following parameters when the output type is MEX Function or Instrumented MEX Function, and you want to use the same setting for C/C++ code generation as well, you must enable it again for C/C++ Static Library, C/C++ Dynamic Library, and C/C++ Executable. Check These MATLAB Coder Project Parameters When Changing Output Type Project Settings Dialog Box Tab Parameter Name Paths Working folder Build folder Search paths Speed Saturate on integer overflow Memory Enable variable-sizing 16-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Selecting Output Type Project Settings Dialog Box Tab Parameter Name Dynamic memory allocation Stack usage max Code Appearance Generated file partitioning method Include comments MATLAB source code as comments Reserved names Debugging Always create a code generation report Automatically launch a report if one is generated Custom Code Source file Header file Initialize function Terminate function Additional include directories Additional source files Additional libraries Post-code-generation command Advanced Constant folding timeout Language Inline threshold Inline threshold max Inline stack limit Use memcpy for vector assignment Memcpy threshold (bytes) Use memset to initialize floats and doubles to 0.0 Check These Command-Line Parameters When Changing Output Type When you switch between MEX and C output types, check these coder.MexCodeConfig, coder.CodeConfig or coder.EmbeddedCodeConfig configuration object parameters, as applicable. 16-43 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Setting Up a MATLAB Coder Project • ConstantFoldingTimeout • CustomHeaderCode • CustomInclude • CustomInitializer • CustomLibrary • CustomSource • CustomSourceCode • CustomTerminator • DynamicMemoryAllocation • EnableMemcpy • EnableVariableSizing • FilePartitionMethod • GenCodeOnly • GenerateComments • GenerateReport • InitFltsAndDblsToZero • InlineStackLimit • InlineThreshold • InlineThresholdMax • LaunchReport • MATLABSourceComments • MemcpyThreshold • PostCodeGenCommand • ReservedNameArray • SaturateOnIntegerOverflow • StackUsageMax • TargetLang 16-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation • “Workflow for Preparing MATLAB Code for Code Generation” on page 17-2 • “Fixing Errors Detected at Design Time” on page 17-4 • “Using the Code Analyzer” on page 17-5 • “Check Code With the Code Analyzer” on page 17-6 • “Check Code Using the Code Generation Readiness Tool” on page 17-8 • “Code Generation Readiness Tool” on page 17-10 • “Unable to Determine Code Generation Readiness” on page 17-17 • “Generate MEX Functions Using the MATLAB Coder Project Interface” on page 17-18 • “Generate MEX Functions at the Command Line” on page 17-26 • “Fix Errors Detected at Code Generation Time” on page 17-28 • “Design Considerations When Writing MATLAB Code for Code Generation” on page 17-29 • “Running MEX Functions” on page 17-31 • “Debugging Strategies” on page 17-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Workflow for Preparing MATLAB Code for Code Generation 17-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Workflow for Preparing MATLAB Code for Code Generation See Also • “MATLAB Coder Project Set Up Workflow” • “Fixing Errors Detected at Design Time” on page 17-4 • “Generate MEX Functions Using the MATLAB Coder Project Interface” • “Fix Errors Detected at Code Generation Time” on page 17-28 • “Workflow for Testing MEX Functions in MATLAB” • “C/C++ Code Generation” • “Accelerate MATLAB Algorithms” 17-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Fixing Errors Detected at Design Time Use the code analyzer and the code generation readiness tool to detect issues at design time. Before generating code, you must fix these issues. See Also • “Check Code With the Code Analyzer” on page 17-6 • “Check Code Using the Code Generation Readiness Tool” on page 17-8 • “Design Considerations When Writing MATLAB Code for Code Generation” on page 17-29 • “Debugging Strategies” on page 17-32 17-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using the Code Analyzer Using the Code Analyzer You use the code analyzer in the MATLAB Editor to check for code violations at design time, minimizing compilation errors. The code analyzer continuously checks your code as you enter it. It reports problems and recommends modifications. To use the code analyzer to identify warnings and errors specific to MATLAB for code generation, you must add the %#codegen directive (or pragma) to your MATLAB file. A complete list of code generation analyzer messages is available in the MATLAB Code Analyzer preferences. For more information, see “Running the Code Analyzer Report”. Note: The code analyzer might not detect all MATLAB for code generation issues. After eliminating the errors or warnings that the code analyzer detects, compile your code with MATLAB Coder to determine if the code has other compliance issues. 17-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Check Code With the Code Analyzer The code analyzer checks your code for problems and recommends modifications. You can use the code analyzer to check your code interactively in the MATLAB Editor while you work. To verify that continuous code checking is enabled: 1 In MATLAB, select the Home tab and then click Preferences. 2 In the Preferences dialog box, select Code Analyzer. 3 In the Code Analyzer Preferences pane, verify that Enable integrated warning and error messages is selected. The code analyzer provides an indicator in the top right of the editor window. If the indicator is green, the analyzer did not detect code generation issues. If the indicator is red, the analyzer has detected errors in your code. If it is orange, it has detected warning. When the indicator is red or orange, a red or orange marker appears to the right of the code where the error occurs. Place your pointer over the marker for information about the error. Click the underlined text in the error message for a more detailed explanation and suggested actions to fix the error. 17-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Check Code With the Code Analyzer Before generating code from your MATLAB code, you must fix the errors detected by the code analyzer. 17-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Check Code Using the Code Generation Readiness Tool In this section... “Run Code Generation Readiness Tool at the Command Line” on page 17-8 “Run Code Generation Readiness Tool from the Current Folder Browser” on page 17-8 “Run the Code Generation Readiness Tool in a Project” on page 17-8 “See Also” on page 17-9 Run Code Generation Readiness Tool at the Command Line 1 Navigate to the folder that contains the file that you want to check for code generation readiness. 2 At the MATLAB command prompt, enter: coder.screener('filename') The Code Generation Readiness tool opens for the file named filename, provides a code generation readiness score, and lists issues that must be fixed prior to code generation. Run Code Generation Readiness Tool from the Current Folder Browser 1 In the current folder browser, right-click the file that you want to check for code generation readiness. 2 From the context menu, select Check Code Generation Readiness. The Code Generation Readiness tool opens for the selected file. It provides a code generation readiness score and lists issues that must be fixed prior to code generation. Run the Code Generation Readiness Tool in a Project 1 After you have added entry-point files to the project, if MATLAB Coder detects code generation issues, it displays a link at the top of the project window. 17-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Check Code Using the Code Generation Readiness Tool 2 Click the link to open the Code Generation Readiness tool. The tool opens and provides a code generation readiness score and lists issues that must be fixed prior to code generation. See Also • “Code Generation Readiness Tool” on page 17-10 17-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Code Generation Readiness Tool In this section... “What Information Does the Code Generation Readiness Tool Provide?” on page 17-10 “Summary Tab” on page 17-11 “Code Structure Tab” on page 17-13 “See Also” on page 17-16 What Information Does the Code Generation Readiness Tool Provide? The code generation readiness tool screens MATLAB code for features and functions that are not supported for code generation. The tool provides a report that lists the source files that contain unsupported features and functions. The report also provides an indication of how much work you must do to make the MATLAB code suitable for code generation. The tool might not detect all code generation issues. Under certain circumstances, it might report false errors. Because the tool might not detect all issues, or might report false errors, generate a MEX function to verify that your code is suitable for code generation before generating C code. 17-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Code Generation Readiness Tool Summary Tab The Summary tab provides a Code Generation Readiness Score which ranges from 1 to 5. A score of 1 indicates that the tool has detected issues that require extensive changes to the MATLAB code to make it suitable for code generation. A score of 5 indicates that the tool has not detected code generation issues; the code is ready to use with no or minimal changes. 17-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation On this tab, the tool also provides information about: • MATLAB syntax issues. These issues are reported in the MATLAB editor. Use the code analyzer to learn more about the issues and how to fix them. • Unsupported MATLAB function calls. • Unsupported MATLAB language features, such as recursion, cell arrays, and nested functions. • Unsupported data types. 17-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Code Generation Readiness Tool Code Structure Tab If the code that you are checking calls other MATLAB functions, or you are checking multiple entry-point functions, the tool displays the Code Structure Tab. This tab provides information about the relative size of each file and how suitable each file is for code generation. 17-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Code Distribution The Code Distribution pane provides a pie chart that shows the relative sizes of the files and how suitable each file is for code generation. This information is useful during the planning phase of a project for estimation and scheduling purposes. If the report indicates that there are multiple files not yet suitable for code generation, consider fixing files that require minor changes before addressing files with significant issues. Call Tree The Call Tree pane provides information on the nesting of function calls. For each called function, the report provides a Code Generation Readiness score which ranges from 1 to 5. A score of 1 indicates that the tool has detected issues that require extensive changes to the MATLAB code to make it suitable for code generation. A score of 5 indicates that the tool has not detected code generation issues; the code is ready to use with no or minimal changes. The report also lists the number of lines of code in each file. Show MATLAB Functions If you select Show MATLAB Functions, the report also lists the MATLAB functions called by your function code. For each of these MATLAB functions, if the function is supported for code generation, the report sets Code Generation Readiness to Yes. 17-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Code Generation Readiness Tool 17-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation See Also • “Check Code Using the Code Generation Readiness Tool” 17-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Unable to Determine Code Generation Readiness Unable to Determine Code Generation Readiness Sometimes the code generation readiness tool cannot determine whether the entry-point functions in your project are suitable for code generation. The most likely reason is that the tool is unable to find the entry-point files. Verify that your current working folder is set to the folder that contains your entry-point files. If it is not, either make this folder your current working folder or add the folder containing these files to the MATLAB path. 17-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Generate MEX Functions Using the MATLAB Coder Project Interface In this section... “Project Workflow for Generating MEX Functions” on page 17-18 “Generate MEX Functions Using the Project Interface” on page 17-18 “Configure Project Settings” on page 17-23 “Build a MATLAB Coder Project” on page 17-24 “See Also” on page 17-25 Project Workflow for Generating MEX Functions Step Action Details 1 Set up your MATLAB Coder project. “Creating a New Project” 2 Fix errors detected by the code analyzer. “Fixing Errors Detected at Design Time” on page 17-4 3 Specify build configuration parameters. “Configure Project Settings” on page 17-23 4 Build the project. “Build a MATLAB Coder Project” on page 17-24 Generate MEX Functions Using the Project Interface In this example, you create a MATLAB function that adds two numbers, then create a MATLAB Coder project for this file. Using the project user interface, you specify types for the function input parameters, and then generate a MEX function for the MATLAB code. 1 In a local writable folder, create a MATLAB file, mcadd.m, that contains: function y = mcadd(u,v) %#codegen y = u + v; 2 In the same folder, set up a MATLAB Coder project. a At the MATLAB command line, enter coder -new mcadd.prj 17-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate MEX Functions Using the MATLAB Coder Project Interface By default, the project opens in the MATLAB workspace on the right side. b On the project Overview tab, click the Add files link, browse to the file mcadd.m, and click Open to add the file to the project. The file is displayed on the Overview tab, and both inputs are undefined. 17-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation c On the Overview tab, click the field to the right of the input parameter u and, from the list of input options, select int16. 17-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate MEX Functions Using the MATLAB Coder Project Interface d From the list of size options, select 1 x 1 to specify that the input is a scalar. 17-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation e 3 Repeat the previous two steps to specify the input v. In the MATLAB Coder project, click the Build tab. By default, the Output type is MEX function and the Output file is mcadd_mex. 17-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate MEX Functions Using the MATLAB Coder Project Interface 4 On this tab, click the Build button to generate a MEX function using the default project settings. MATLAB Coder builds the project and, by default, generates a MEX function, mcadd_mex, in the current folder. MATLAB Coder also generates other supporting files in a subfolder called codegen/mex/mcadd. MATLAB Coder uses the name of the MATLAB function as the root name for the generated files and creates a platform-specific extension for the MEX file, as described in “Naming Conventions” on page 19-66. You can now test your MEX function in MATLAB. For more information, see “Verify MEX Functions in a Project”. Configure Project Settings 1 On the project Build tab, click the More settings link to view the project settings for the selected output type. Note: MEX functions use a different set of configuration parameters than C/C++ libraries and executables. When you change the output type from MEX Function or Instrumented MEX Function to C/C++ Static Library, C/C++ Dynamic Libraryor C/C++ Executable, verify these settings. For more information, see “Changing Output Type” on page 16-42. 17-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation 2 In the Project Settings dialog box, select the settings that you want to apply. Tip To learn more about the configuration parameters on the current tab of the Project Settings dialog box, click the Help button. See Also • “How to Enable Code Generation Reports in the Project Settings Dialog Box” on page 19-170 • “In the Project Settings Dialog Box” on page 19-114 • “How to Disable Inlining Globally in the Project Settings Dialog Box” on page 19-124 • “Generate Traceable Code” on page 19-84 • “Disabling Run-Time Checks in the Project Settings Dialog Box” on page 23-17 Build a MATLAB Coder Project On the project Build tab, click the Build button to build the project using the specified settings. While MATLAB Coder builds a project, it displays the build progress in the Build dialog box. When the build is complete, MATLAB Coder provides details in the Build Results pane. Viewing Build Results The Build Results pane provides information about the most recent build. If the code generation report is enabled or build errors occur, MATLAB Coder generates a report that provides detailed information about the most recent build and provides a link to the report. To view the report, click the View report link. After a build completes, this report provides links to your MATLAB code and generated C/C++ files as well as compile-time type information for the variables in your MATLAB code. If build errors occur, it lists errors and warnings. Saving Build Results When MATLAB Coder builds a project, it displays the build progress and results in the Build dialog box. To save the build results, click the Save to log file link and specify the log file location. 17-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate MEX Functions Using the MATLAB Coder Project Interface See Also • “Code Generation Reports” • “Generate Code for Multiple Entry-Point Functions” on page 19-70 • “Generate Code for Global Data” on page 19-75 See Also • “Generate Code for Multiple Entry-Point Functions” on page 19-70 • “Generate Code for Global Data” on page 19-75 • “Specify Output File Name” • “Specify Output File Locations” 17-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Generate MEX Functions at the Command Line Command-line Workflow for Generating MEX Functions Step Action Details 1 Install prerequisite products. “Installing Prerequisite Products” 2 Set up your file infrastructure. “Paths and File Infrastructure Setup” on page 19-65 3 Fix errors detected by the code analyzer. “Fixing Errors Detected at Design Time” on page 17-4 4 Specify build configuration parameters. “Specify Build Configuration Parameters” on page 19-25 5 Specify properties of primary function inputs. “Primary Function Input Specification” on page 19-39 6 Generate the MEX function using codegen with suitable command-line options. “Generating MEX Functions at the Command Line Using codegen” on page 17-27 Generate MEX Functions at the Command Line In this example, you use the codegen function to generate a MEX function from a MATLAB file that adds two inputs. You use the codegen -args option to specify that both inputs are int16. 1 In a local writable folder, create a MATLAB file, mcadd.m, that contains: function y = mcadd(u,v) %#codegen y = u + v; 2 Generate a platform-specific MEX function in the current folder. At the command line, specify that the two input parameters are int16 using the -args option. By default, if you do not use the -args option, codegen treats inputs as real, scalar doubles. codegen mcadd -args {int16(0), int16(0)} codegen generates a MEX function, mcadd_mex, in the current folder. codegen also generates other supporting files in a subfolder called codegen/mex/mcadd.codegen uses the name of the MATLAB function as the root name for the generated files 17-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate MEX Functions at the Command Line and creates a platform-specific extension for the MEX file, as described in “Naming Conventions” on page 19-66. Generating MEX Functions at the Command Line Using codegen You generate a MEX function at the command line using the codegen function. The basic command is: codegen fcn By default, codegen generates a MEX function in the current folder as described in “Generate MEX Functions at the Command Line”. You can modify this default behavior by specifying one or more compiler options with codegen, separated by spaces on the command line. For more information, see codegen. See Also • “Primary Function Input Specification” • “MEX Function Generation at the Command Line” • “Generate Code for Multiple Entry-Point Functions” on page 19-70 • “Generate Code for Global Data” on page 19-75 17-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Fix Errors Detected at Code Generation Time When the code generation software detects errors or warnings, it automatically generates an error report. The error report describes the issues and provides links to the MATLAB code with errors. To fix the errors, modify your MATLAB code to use only those MATLAB features that are supported for code generation. For more information, see “MATLAB Algorithm Design Basics”. Choose a debugging strategy for detecting and correcting code generation errors in your MATLAB code. For more information, see “Debugging Strategies”. When code generation is complete, the software generates a MEX function that you can use to test your implementation in MATLAB. If your MATLAB code calls functions on the MATLAB path, unless the code generation software determines that these functions should be extrinsic or you declare them to be extrinsic, it attempts to compile these functions. See “Resolution of Function Calls for Code Generation”. To get detailed diagnostics, add the %#codegen directive to each external function that you want codegen to compile. See Also • “Code Generation Reports” • “Why Test MEX Functions in MATLAB?” • “When to Generate Code from MATLAB Algorithms” • “Debugging Strategies” • “Declaring MATLAB Functions as Extrinsic Functions” 17-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Design Considerations When Writing MATLAB Code for Code Generation Design Considerations When Writing MATLAB Code for Code Generation When writing MATLAB code that you want to convert into efficient, standalone C/C++ code, you must consider the following: • Data types C and C++ use static typing. To determine the types of your variables before use, MATLAB Coder requires a complete assignment to each variable. • Array sizing Variable-size arrays and matrices are supported for code generation. You can define inputs, outputs, and local variables in MATLAB functions to represent data that varies in size at run time. • Memory You can choose whether the generated code uses static or dynamic memory allocation. With dynamic memory allocation, you potentially use less memory at the expense of time to manage the memory. With static memory, you get best speed, but with higher memory usage. Most MATLAB code takes advantage of the dynamic sizing features in MATLAB, therefore dynamic memory allocation typically enables you to generate code from existing MATLAB code without modifying it much. Dynamic memory allocation also allows some programs to compile even when upper bounds cannot be found. Static allocation reduces the memory footprint of the generated code, and therefore is suitable for applications where there is a limited amount of available memory, such as embedded applications. • Speed Because embedded applications must run in real time, the code must be fast enough to meet the required clock rate. To improve the speed of the generated code: • Choose a suitable C or /C++ compiler. The default compiler that MathWorks supplies with MATLAB for Windows 32-bit platforms is not a good compiler for performance. 17-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation • Consider disabling run-time checks. By default, the code generated for your MATLAB code contains memory integrity checks and responsiveness checks. Generally, these checks result in more generated code and slower MEX function execution. Disabling run-time checks usually results in streamlined generated code and faster MEX function execution. Disable these checks only if you have verified that array bounds and dimension checking is unnecessary. See Also • “MATLAB Algorithm Design Basics” • “Data Definition” • “Variable-Size Data” • “Bounded Versus Unbounded Variable-Size Data” • “Control Dynamic Memory Allocation” on page 19-95 • “Control Run-Time Checks” 17-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Running MEX Functions Running MEX Functions When you call a MEX function, pass it the same inputs you use for the original MATLAB algorithm. Do not pass coder.Constant or any of the coder.Type classes to a MEX function; these classes are for use with the codegen function. To run a MEX function generated by MATLAB Coder, you must have licenses for all the toolboxes that the MEX function requires. For example, if you generate a MEX function from a MATLAB algorithm that uses a Computer Vision System Toolbox function or System object, to run the MEX function, you must have a Computer Vision System Toolbox license. When you upgrade MATLAB, before running MEX functions with the new version, rebuild the MEX functions. Debugging MEX Functions You cannot use the disp and save functions during debugging to inspect the contents of your MEX function variables. Because these functions are not supported for code generation, you must declare them as extrinsic functions. For extrinsic functions, when running the MEX function, MATLAB Coder calls out to MATLAB to run disp and save, so they save and display the data found in the base workspace, not the MEX-function workspace. 17-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 17 Preparing MATLAB Code for C/C++ Code Generation Debugging Strategies Before you perform code verification, choose a debugging strategy for detecting and correcting noncompliant code in your MATLAB applications, especially if they consist of a large number of MATLAB files that call each other's functions. The following table describes two general strategies, each of which has advantages and disadvantages. Debugging Strategy What to Do Bottom-up 1 verification 2 Top-down 1 verification Pros Cons Verify that your lowestlevel (leaf) functions are compliant. • Efficient Work your way up the function hierarchy incrementally to compile and verify each function, ending with the top-level function. • Easy to isolate code generation syntax violations Declare functions called by the top-level function to be extrinsic so that MATLAB Coder does not compile them. See “Declaring MATLAB Functions as Extrinsic Functions”. You retain your top- Introduces extraneous code level tests that you must remove after code verification, including: 2 Verify that your top-level function is compliant. 3 Work your way down the function hierarchy incrementally by removing extrinsic declarations one by one to compile and verify each function, ending with the leaf functions. Requires application tests that • Unlikely to cause work from the bottom up errors 17-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان • Extrinsic declarations • Additional assignment statements as required to convert opaque values returned by extrinsic functions to nonopaque values (see “Working with mxArrays”). 18 Testing MEX Functions in MATLAB • “Workflow for Testing MEX Functions in MATLAB” on page 18-2 • “Why Test MEX Functions in MATLAB?” on page 18-4 • “Running MEX Functions” on page 18-5 • “Verify MEX Functions in a Project” on page 18-6 • “Verify MEX Functions at the Command Line” on page 18-8 • “Debug Run-Time Errors” on page 18-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 18 Testing MEX Functions in MATLAB Workflow for Testing MEX Functions in MATLAB See Also • “MATLAB Coder Project Set Up Workflow” • “Workflow for Preparing MATLAB Code for Code Generation” 18-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Workflow for Testing MEX Functions in MATLAB • “Why Test MEX Functions in MATLAB?” on page 18-4 • “Debug Run-Time Errors” on page 18-9 • “C/C++ Code Generation” • “Accelerate MATLAB Algorithms” 18-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 18 Testing MEX Functions in MATLAB Why Test MEX Functions in MATLAB? Before generating C/C++ code for your MATLAB code, it is a best practice to test the MEX function to verify that it provides the same functionality as the original MATLAB code. To do this testing, run the MEX function using the same inputs as you used to run the original MATLAB code and compare the results. For more information about how to test a MEX function in a project, see “Verify MEX Functions in a Project” on page 18-6. For more information on how to test a MEX function at the command line, see “Verify MEX Functions at the Command Line” on page 18-8. In addition, running the MEX function in MATLAB before generating code enables you to detect and fix run-time errors that are much harder to diagnose in the generated code. If you encounter run-time errors in your MATLAB functions, fix them before generating code. For more information, see “Debug Run-Time Errors” on page 18-9. When you run your MEX function in MATLAB, by default, the following run-time checks execute : • Memory integrity checks. These checks perform array bounds checking, dimension checking, and detect violations of memory integrity in code generated for MATLAB functions. If a violation is detected, MATLAB stops execution and provides a diagnostic message. • Responsiveness checks in code generated for MATLAB functions. These checks enable periodic checks for Ctrl+C breaks in code generated for MATLAB functions, allowing you to terminate execution with Ctrl+C. For more information, see “Control Run-Time Checks”. 18-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Running MEX Functions Running MEX Functions When you call a MEX function, pass it the same inputs you use for the original MATLAB algorithm. Do not pass coder.Constant or any of the coder.Type classes to a MEX function; these classes are for use with the codegen function. To run a MEX function generated by MATLAB Coder, you must have licenses for all the toolboxes that the MEX function requires. For example, if you generate a MEX function from a MATLAB algorithm that uses a Computer Vision System Toolbox function or System object, to run the MEX function, you must have a Computer Vision System Toolbox license. When you upgrade MATLAB, before running MEX functions with the new version, rebuild the MEX functions. Debugging MEX Functions You cannot use the disp and save functions during debugging to inspect the contents of your MEX function variables. Because these functions are not supported for code generation, you must declare them as extrinsic functions. For extrinsic functions, when running the MEX function, MATLAB Coder calls out to MATLAB to run disp and save, so they save and display the data found in the base workspace, not the MEX-function workspace. 18-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 18 Testing MEX Functions in MATLAB Verify MEX Functions in a Project In this section... “Using Test Files That Call Only MATLAB Functions” on page 18-6 “Using Test Files That Call MEX Functions” on page 18-7 Using Test Files That Call Only MATLAB Functions If you have a test file that calls only your original entry-point MATLAB function, use the following procedure. A test file can be either a MATLAB function or a script. To use this procedure, you should verify that it calls at least one entry-point function. The generated MEX function must be in the same folder as the entry-point functions. Selecting the Redirect entry-point calls to MEX function option directs MATLAB Coder software to replace calls to the MATLAB function with calls to the generated MEX function. This capability allows you to compare the behavior of the MEX function with that of the original function. If your test file calls the generated MEX function, do not follow this procedure. Instead, follow the procedure in “Using Test Files That Call MEX Functions” on page 18-7. 1 On the project Build tab Verification panel, click the button to add a test file. Alternatively, if you have already added test files to the project, select one from the list. 2 Run the test file calling the original MATLAB algorithm. a Clear Redirect entry-point calls to MEX function. b Click the Run button. The test file runs and calls your original MATLAB algorithm. 3 Verify that the test results are as expected. 4 Run the test file calling the MEX function instead of the original MATLAB algorithm. a Select Redirect entry-point calls to MEX function. b Click the Run button. 18-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Verify MEX Functions in a Project The project builds the MEX function. The test file runs and automatically replaces calls to your original MATLAB algorithm with calls to the generated MEX function. 5 Compare the results of the two runs to verify that the MEX function provides the same functionality as the original MATLAB algorithm. Using Test Files That Call MEX Functions If you have a test file that calls the generated MEX function, use the following procedure. If your test file calls both the original MATLAB function and the generated MEX function, you can also use this procedure. A test file can be either a MATLAB function or a script. To use this procedure, you should verify that it calls at least one MEX function. The MEX function must be in the same folder as the entry-point functions. 1 On the project Build tab Verification panel, click the button to add a test file. Alternatively, if you have already added test files to the project, select one from the list. 2 Run the test file. a Clear Redirect entry-point calls to MEX function. Because the test file already calls the MEX function, you do not want MATLAB Coder to redirect entry-point function calls. b Click the Run button. The project builds the MEX function. The test file runs and calls the generated MEX function. If applicable, it also calls the original MATLAB algorithm. 3 Use the results of this run to verify that the MEX function provides the same functionality as the original MATLAB algorithm. 18-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 18 Testing MEX Functions in MATLAB Verify MEX Functions at the Command Line If you have a test file that calls your original MATLAB function, use coder.runTest to verify the MEX function at the command line. coder.runTest runs the test file replacing calls to the original MATLAB function with calls to the generated MEX function. If errors occur during the run with coder.runTest, call stack information is available for debugging purposes. For more information, see the coder.runTest function reference information and “Verifying the MEX Function” in the MATLAB Coder “C Code Generation at the Command Line” tutorial. 18-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Debug Run-Time Errors Debug Run-Time Errors In this section... “Viewing Errors in the Run-Time Stack” on page 18-9 “Handling Run-Time Errors” on page 18-10 If you encounter run-time errors in your MATLAB functions, the run-time stack appears automatically in the MATLAB command window. Use the error message and stack information to learn more about the source of the error and then either fix the issue or add error-handling code. For more information, see “Viewing Errors in the Run-Time Stack” on page 18-9“Handling Run-Time Errors” on page 18-10. Viewing Errors in the Run-Time Stack About the Run-Time Stack The run-time stack is enabled by default for MEX code generation from MATLAB. Use the error message and the following stack information to learn more about the source of the error: • The name of the function that generated the error • The line number of the attempted operation • The sequence of function calls that led up to the execution of the function and the line at which each of these function calls occurred Example Run-Time Stack Trace This example shows the run-time stack trace for MEX function mlstack_mex: mlstack_mex(-1) Index exceeds matrix dimensions. Index value -1 exceeds valid range [1-4] of array x. Error in mlstack>mayfail (line 31) y = x(u); Error in mlstack>subfcn1 (line 5) switch (mayfail(u)) 18-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 18 Testing MEX Functions in MATLAB Error in mlstack (line 2) y = subfcn1(u); The stack trace provides the following information: • The type of error. ??? Index exceeds matrix dimensions. Index value -1 exceeds valid range [1-4] of array x. • Where the error occurred. Error in ==>mlstack>mayfail at 31 y = x(u); • The function call sequence prior to the failure. Error in ==> mlstack>subfcn1 at 5 switch (mayfail(u)) Error in ==> mlstack at 2 y = subfcn1(u); When to Use the Run-Time Stack The run-time stack is useful during debugging to help you find the source of run-time errors. However, when the stack is enabled, the generated code contains instructions for maintaining the run-time stack, which might slow the run time. Consider disabling the run-time stack for faster run time. How to Disable the Run-Time Stack You can disable the run-time stack by disabling the memory integrity checks as described in “How to Disable Run-Time Checks”. Caution Before disabling the memory integrity checks, you should verify that all array bounds and dimension checking is unnecessary. Handling Run-Time Errors The code generation software propagates error ID's. If you throw an error or warning in your MATLAB code, use the try-catch statement in your test bench code to examine 18-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Debug Run-Time Errors the error information and attempt to recover, or clean up and abort. For example, for the function in “Example Run-Time Stack Trace” on page 18-9, create a test script containing: try mlstack_mex(u) catch % Add your error handling code here end For more information, see “ The try/catch Statement”. 18-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 18-12 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code • “Code Generation Workflow” on page 19-3 • “C/C++ Code Generation” on page 19-5 • “Generating C/C++ Static Libraries from MATLAB Code” on page 19-6 • “Generating C/C++ Dynamically Linked Libraries from MATLAB Code” on page 19-10 • “Generating Standalone C/C++ Executables from MATLAB Code” on page 19-13 • “Build Setting Configuration” on page 19-19 • “Standard Math Libraries” on page 19-32 • “Change the Standard Math Library” on page 19-33 • “Share Build Configuration Settings” on page 19-34 • “Convert MATLAB Coder Project to MATLAB Script” on page 19-37 • “Primary Function Input Specification” on page 19-39 • “Control Constant Inputs in MEX Function Signatures” on page 19-49 • “Define Input Properties Programmatically in the MATLAB File” on page 19-53 • “Speed Up Compilation” on page 19-63 • “Paths and File Infrastructure Setup” on page 19-65 • “Generate Code for Multiple Entry-Point Functions” on page 19-70 • “Generate Code for Global Data” on page 19-75 • “Generation of Traceable Code” on page 19-84 • “Generate Code for Enumerated Types” on page 19-93 • “Generate Code for Variable-Size Data” on page 19-94 • “Code Generation for MATLAB Classes” on page 19-113 • “How MATLAB Coder Partitions Generated Code” on page 19-114 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code • “Requirements for Signed Integer Representation” on page 19-126 • “Customize the Post-Code-Generation Build Process” on page 19-127 • “Code Generation Reports” on page 19-167 • “Troubleshooting” on page 19-186 • “Package Code For Other Development Environments” on page 19-187 19-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Code Generation Workflow Code Generation Workflow See Also • “MATLAB Coder Project Set Up Workflow” 19-3 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code • “Workflow for Preparing MATLAB Code for Code Generation” • “Workflow for Testing MEX Functions in MATLAB” • “Build Setting Configuration” on page 19-19 • “C/C++ Code Generation” on page 19-5 19-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان C/C++ Code Generation C/C++ Code Generation Using MATLAB Coder, you can generate standalone C/C++ static and dynamic libraries and C/C++ executables. If you specify C++, MATLAB Coder wraps the C code into .cpp files so that you can use a C++ compiler and interface with external C++ applications. It does not generate C++ classes. By default, if MATLAB Coder does not detect errors, it generates a platform-specific MEX function in the current folder. To learn how to generate... See... C/C++ static libraries from your MATLAB code “Generating C/C++ Static Libraries from MATLAB Code” on page 19-6 C/C++ dynamic libraries from your MATLAB code “Generating C/C++ Dynamically Linked Libraries from MATLAB Code” on page 19-10 C/C++ executables from your MATLAB code “Generating Standalone C/C++ Executables from MATLAB Code” on page 19-13 MEX functions from your MATLAB code “Generate MEX Functions Using the MATLAB Coder Project Interface” If errors occur, MATLAB Coder does not generate code, but produces an error report and provides a link to this report. For more information, see “Code Generation Reports” on page 19-167. Specify Custom Files to Build In addition to your MATLAB file, you can specify the following types of custom files to include in the build for standalone C/C++ code generation. File Extension Description .c Custom C file .cpp Custom C++ file .h Custom header file .o , .obj Custom object file .a , .lib, .so Library .tmf Template makefile for custom MATLAB Coder builds 19-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Generating C/C++ Static Libraries from MATLAB Code In this section... “Generate a C Static Library Using the Project Interface” on page 19-6 “Generate a C Static Library at the Command Line” on page 19-9 Generate a C Static Library Using the Project Interface This example shows how to generate a C static library from MATLAB code using a MATLAB Coder project. In this example, you create a MATLAB function that adds two numbers. You then create a MATLAB Coder project. Use the project user interface to generate a C static library for the MATLAB code. 1 In a local writable folder, create a MATLAB file, mcadd.m, that contains: function y = mcadd(u,v) %#codegen y = u + v; 2 In the same folder, set up a MATLAB Coder project. a At the MATLAB command line, enter: coder -new mcadd.prj By default, the project opens in the MATLAB workspace on the right side. b On the project Overview tab, click the Add files link. Browse to the file mcadd.m. Click OK to add the file to the project. The file is displayed on the Overview tab. Both inputs are undefined. 3 Define the type of input u. a On the Overview tab, click the field to the right of the input parameter u and, from the list of input options, select int16. 19-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generating C/C++ Static Libraries from MATLAB Code b From the list of size options, select 1 x 1 to specify that the input is a scalar. 19-7 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code 4 Repeat the previous step for input v. 5 In the MATLAB Coder project, click the Build tab. 6 On this tab, set the Output type to C/C++ Static library. The default output file name is mcadd. 7 Click Build to generate a library using the default project settings. MATLAB Coder builds the project and generates a C static library and supporting files in the default folder, codegen/lib/mcadd. It generates the minimal set of 19-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generating C/C++ Static Libraries from MATLAB Code #include statements for header files required by the selected code replacement library. Generate a C Static Library at the Command Line This example shows how to generate a C static library from MATLAB code at the command line using the codegen function. 1 In a local writable folder, create a MATLAB file, mcadd.m, that contains: function y = mcadd(u,v) %#codegen y = u + v; 2 Using the config:lib option, generate C library files. Using the -args option, specify that the first input is a 1-by-4 vector of unsigned 16-bit integers and that the second input is a double-precision scalar. codegen -config:lib mcadd -args {zeros(1,4,'uint16'),0} MATLAB Coder generates a C static library with the default name, mcadd, and supporting files in the default folder, codegen/lib/mcadd. It generates the minimal set of #include statements for header files required by the selected code replacement library. 19-9 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Generating C/C++ Dynamically Linked Libraries from MATLAB Code In this section... “Dynamic Libraries Generated by MATLAB Coder” on page 19-10 “Generate a C Dynamically Linked Library (DLL) Using the Project Interface” on page 19-10 “Generate a C Dynamic Library at the Command Line” on page 19-12 Dynamic Libraries Generated by MATLAB Coder By default, when MATLAB Coder generates a dynamic library (DLL): • The DLL is suitable for the platform that you are working on. • The DLL uses the release version of the C run-time library. • The DLL linkage conforms to the target language, by default, C. If you set the target language to C++, the linkage conforms to C++. • When the target language is C, the generated header files explicitly declare the exported functions to be extern "C" to simplify integration of the DLL into C++ applications. If you generate a DLL that uses dynamically allocated variable-size data, MATLAB Coder automatically provides exported utility functions to interact with this data in the generated code. For more information, see “Utility Functions for Creating emxArray Data Structures”. Generate a C Dynamically Linked Library (DLL) Using the Project Interface This example shows how to generate a C DLL from MATLAB code using a MATLAB Coder project. In this example, you create a MATLAB function that generates a random scalar value. You then create a MATLAB Coder project. Use the project user interface to generate a C dynamic library for the MATLAB code. 1 Write two MATLAB functions, ep1 takes one input, a single scalar, and ep2 takes two inputs, both double scalars. In a local writable folder, create a MATLAB file, ep1.m, that contains: 19-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generating C/C++ Dynamically Linked Libraries from MATLAB Code function y = ep1(u) %#codegen y = u; In the same folder, create a MATLAB file, ep2.m, that contains: function y = ep2(u, v) %#codegen y = u + v; 2 In the same folder as the ep1 and ep2 files, set up a MATLAB Coder project. At the MATLAB command line, enter: coder -new ep.prj By default, the project opens in the MATLAB workspace on the right side. 3 On the project Overview tab, click the Add files link and browse to the file ep1.m . Click OK to add the file to the project. The file is displayed on the Overview tab. MATLAB Coder indicates that input u is undefined. 4 5 Define the type of input u. a On the Overview tab, click the field to the right of the input parameter u and then, from the list of input options, select single. b From the list of size options, select 1 x 1 to specify that u is a scalar. On the project Overview tab, click the Add files link and browse to the file ep2.m . Click OK to add the file to the project. The file is displayed on the Overview tab. MATLAB Coder indicates that inputs u and v are undefined. 6 Define the type of input u. a On the Overview tab, click the field to the right of the input parameter u and then, from the list of input options, select double. b From the list of size options, select 1 x 1 to specify that u is a scalar. 7 Repeat the previous step for input v. 8 In the MATLAB Coder project, click the Build tab. 9 On the Build tab, set the Output type to C/C++ Dynamic Library. 10 On the Build tab, click the Build button to generate a library using these project settings. 19-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code On Microsoft® Windows systems, MATLAB Coder generates a C dynamic library, ep1.dll, and supporting files, in the default folder, codegen/dll/ep1. It generates the minimal set of #include statements for header files required by the selected code replacement library. On Linux and Macintosh systems, it generates a shared object (.so) file. The DLL linkage conforms to the target language, in this example, C. If you set the target language to C++, the linkage conforms to C++. Generate a C Dynamic Library at the Command Line This example shows how to generate a C dynamic library from MATLAB code at the command line using the codegen function. 1 Write two MATLAB functions, ep1 takes one input, a single scalar, and ep2 takes two inputs, both double scalars. In a local writable folder, create a MATLAB file, ep1.m, that contains: function y = ep1(u) %#codegen y = u; In the same folder, create a MATLAB file, ep2.m, that contains: function y = ep2(u, v) %#codegen y = u + v; 2 Generate the C dynamic library. codegen -config:dll ep1 -args single(0) ep2 -args {0,0} On Microsoft Windows systems, codegen generates a C dynamic library, ep1.dll, and supporting files, in the default folder, codegen/dll/ep1. It generates the minimal set of #include statements for header files required by the selected code replacement library. On Linux and Macintosh systems, it generates a shared object (.so) file. The DLL linkage conforms to the target language, in this example, C. If you set the target language to C++, the linkage conforms to C++. Note: The default target language is C. To change the target language to C++, see “Specify a Language for Code Generation” on page 19-21. 19-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generating Standalone C/C++ Executables from MATLAB Code Generating Standalone C/C++ Executables from MATLAB Code In this section... “Generate a C Executable Using the Project Interface” on page 19-13 “Generate a C Executable at the Command Line” on page 19-15 “Specifying main Functions for C/C++ Executables” on page 19-16 “Specify main Functions” on page 19-17 Generate a C Executable Using the Project Interface In this example, you create a MATLAB function that generates a random scalar value and a main C function that calls this MATLAB function. You then create a MATLAB Coder project. Use the project user interface to specify types for the function input parameters, specify the main function, and generate a C executable for the MATLAB code. 1 Write a MATLAB function, coderand, that generates a random scalar value from the standard uniform distribution on the open interval (0,1): function r = coderand() %#codegen r = rand(); 2 Write a main C function, c:\myfiles\main.c, that calls coderand. For example: /* ** main.c */ #include <stdio.h> #include <stdlib.h> #include "coderand.h" #include "coderand_initialize.h" #include "coderand_terminate.h" int main() { coderand_initialize(); printf("coderand=%g\n", coderand()); coderand_terminate(); 19-13 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code return 0; } Note: In this example, because the default file partitioning method is to generate one file for each MATLAB file, you include coderand_initialize.h and coderand_terminate.h. If your file partitioning method is set to generate one file for all functions, do not include coderand_initialize.h and coderand_terminate.h. 3 In the same folder as the coderand file, set up a MATLAB Coder project. a At the MATLAB command line, enter: coder -new coderand.prj By default, the project opens in the MATLAB workspace on the right side. b On the project Overview tab, click the Add files link and browse to the file coderand.m . Click OK to add the file to the project. The file is displayed on the Overview tab. MATLAB Coder indicates that the coderand function has no inputs. 4 In the MATLAB Coder project, click the Build tab. a Set the Output type to C/C++ Executable. b Set the output file name to coderand_exe. 5 On the project Build tab, click the More settings link. 6 On the Project Settings dialog box Custom Code tab, under Additional files and directories to be built, set: a Source files to main.c, which is the name of the C/C++ source file that contains the main function. b Include directories to the location of main.c: c:\myfiles. c Close the dialog box. Note: When you are building an executable, you must specify the main function. For more information, see “Specifying main Functions for C/C++ Executables” on page 19-16. 19-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generating Standalone C/C++ Executables from MATLAB Code 7 On the Build tab, click the Build button to generate a library using the default project settings. MATLAB Coder compiles and links the main function with the C code that it generates for the project and, in the current folder, generates an executable, coderand_exe. It generates supporting files in the default folder, codegen/exe/ coderand. MATLAB Coder generates the minimal set of #include statements for header files required by the selected code replacement library. See Also • “MATLAB Coder Project Set Up Workflow” • “Workflow for Preparing MATLAB Code for Code Generation” • “Workflow for Testing MEX Functions in MATLAB” • “Build Setting Configuration” on page 19-19 • “C/C++ Code Generation” on page 19-5 • “Optimization Strategies” Generate a C Executable at the Command Line In this example, you create a MATLAB function that generates a random scalar value and a main C function that calls this MATLAB function. You then specify types for the function input parameters, specify the main function, and generate a C executable for the MATLAB code. 1 Write a MATLAB function, coderand, that generates a random scalar value from the standard uniform distribution on the open interval (0,1): function r = coderand() %#codegen r = rand(); 2 Write a main C function, c:\myfiles\main.c, that calls coderand. For example: /* ** main.c */ #include <stdio.h> #include <stdlib.h> #include "coderand.h" #include "coderand_initialize.h" #include "coderand_terminate.h" 19-15 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code int main() { coderand_initialize(); printf("coderand=%g\n", coderand()); coderand_terminate(); return 0; } Note: In this example, because the default file partitioning method is to generate one file for each MATLAB file, you include “coderand_initialize.h” and “coderand_terminate.h”. If your file partitioning method is set to generate one file for all functions, do not include “coderand_initialize.h” and “coderand_terminate.h”. 3 Configure your code generation parameters to include the main C function and then generate the C executable: cfg = coder.config('exe'); cfg.CustomSource = 'main.c'; cfg.CustomInclude = 'c:\myfiles'; codegen -config cfg coderand codegen generates a C executable, coderand.exe, in the current folder. It generates supporting files in the default folder, codegen/exe/coderand. codegen generates the minimal set of #include statements for header files required by the selected code replacement library. Specifying main Functions for C/C++ Executables When you generate an executable, you must provide a main function. If you are generating a C executable, provide a C file, main.c. If you are generating a C++ executable, provide a C++ file, main.cpp. Verify that the folder containing the main function has only one main file. Otherwise, main.c takes precedence over main.cpp, which causes an error when generating C++ code. You can specify the main file from the project settings dialog box, the command line, or the Code Generation dialog box. When you convert a MATLAB function to a C/C++ library function or a C/C++ executable, MATLAB Coder automatically generates an initialize function and a terminate function. 19-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generating Standalone C/C++ Executables from MATLAB Code • If your file partitioning method is set to generate one file for each MATLAB file, you must include the initialize and terminate header functions in main.c. Otherwise, do not include them in main.c. • You must call these functions along with the C/C++ function. For more information, see “Calling Initialize and Terminate Functions” on page 22-7. Specify main Functions Specifying main Functions in the Project Settings Dialog Box 1 On the project Build tab, click the More settings link to open the Project Settings dialog box. 2 On the Custom Code tab, set: a Additional source files to the name of the C/C++ source file that contains the main function. For example, main.c. For more information, see “Specifying main Functions for C/C++ Executables” on page 19-16. b Additional include directories to the location of main.c. For example, c: \myfiles. Specifying main Functions at the Command Line Set the CustomSource and CustomInclude properties of the code generation configuration object (see “Working with Configuration Objects” on page 19-27). The CustomInclude property indicates the location of C/C++ files specified by CustomSource. 1 Create a configuration object for an executable: cfg = coder.config('exe'); 2 Set the CustomSource property to the name of the C/C++ source file that contains the main function. (For more information, see “Specifying main Functions for C/C++ Executables” on page 19-16.) For example: cfg.CustomSource = 'main.c'; 3 Set the CustomInclude property to the location of main.c. For example: cfg.CustomInclude = 'c:\myfiles'; 4 Generate the C/C++ executable using the command line options. For example, if myFunction takes one input parameter of type double: 19-17 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code codegen -config cfg myMFunction -args {0} MATLAB Coder compiles and links the main function with the C/C++ code that it generates from myMFunction.m. 19-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Build Setting Configuration Build Setting Configuration In this section... “Specify Output Type” on page 19-19 “Specify a Language for Code Generation” on page 19-21 “Specify Data Type Used in Generated Code” on page 19-22 “Specify Output File Name” on page 19-23 “Specify Output File Locations” on page 19-24 “Parameter Specification Methods” on page 19-25 “Specify Build Configuration Parameters” on page 19-25 Specify Output Type Output Types MATLAB Coder can generate code for the following output types: • MEX function • Instrumented MEX function • Standalone C/C++ code and compile it to a static library • Standalone C/C++ code and compile it to a dynamically-linked library • Standalone C/C++ code and compile it to an executable Note: When you generate an executable, you must provide a C/C++ file that contains the main function, as described in “Specifying main Functions for C/C++ Executables” on page 19-16. Location of Generated Files By default, MATLAB Coder generates files in output folders based on your output type. For more information, see “Generated Files and Locations” on page 19-120. Note: Each time MATLAB Coder generates the same type of output for the same code or project, it removes the files from the previous build. If you want to preserve files from a build, copy them to a different location before starting another build. 19-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Specifying the Output Type Using the MATLAB Coder Project Interface On the MATLAB Coder project Build tab, set Output type to one of the available output types: • MEX Function (default) • Instrumented MEX Function • C/C++ Static Library • C/C++ Dynamic Library • C/C++ Executable MEX functions use a different set of configuration parameters than C/C++ libraries and executables. When you switch the output type between MEX Function or Instrumented MEX Function and C/C++ Static Library, C/C++ Dynamic Library or C/C++ Executable, verify these settings. For more information, see “Changing Output Type” on page 16-42. Specifying the Output Type at the Command Line Call codegen with the -config option. For example, suppose you have a primary function foo that takes no input parameters. The following table shows how to specify different output types when compiling foo. If a primary function has input parameters, you must specify these inputs. For more information, see “Primary Function Input Specification” on page 19-39. Note: C is the default language for code generation with MATLAB Coder. To generate C+ + code, see “Specify a Language for Code Generation” on page 19-21. To Generate: MEX function using the default code generation options MEX function specifying code generation options Use This Command: codegen foo cfg = coder.config('mex'); % Set configuration parameters, for example, % enable a code generation report cfg.GenerateReport=true; % Call codegen, passing the configuration % object 19-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Build Setting Configuration To Generate: Use This Command: codegen -config cfg foo Standalone C/C++ code and compile it to a library using the default code generation options Standalone C/C++ code and compile it to a library specifying code generation options Standalone C/C++ code and compile it to an executable using the default code generation options and specifying the main.c file at the command line Standalone C/C++ code and compile it to an executable specifying code generation options codegen -config:lib foo cfg = coder.config('lib'); % Set configuration parameters, for example, % enable a code generation report cfg.GenerateReport=true; % Call codegen, passing the configuration % object codegen -config cfg foo codegen -config:exe main.c foo Note: You must specify a main function for generating a C/ C++ executable. See “Specifying main Functions for C/C++ Executables” on page 19-16 cfg = coder.config('exe'); % Set configuration parameters, for example, % specify main file cfg.CustomSource = 'main.c'; cfg.CustomInclude = 'c:\myfiles'; codegen -config cfg foo Note: You must specify a main function for generating a C/ C++ executable. See “Specifying main Functions for C/C++ Executables” on page 19-16 Specify a Language for Code Generation • “Specifying a Language for Code Generation in the Project Settings Dialog Box” on page 19-22 • “Specifying a Language for Code Generation at the Command Line” on page 19-22 MATLAB Coder can generate C or C++ libraries and executables. C is the default language. You can specify a language explicitly from the project settings dialog box or at the command line. 19-21 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Specifying a Language for Code Generation in the Project Settings Dialog Box 1 Select a suitable compiler for your target language. 2 On the MATLAB Coder project Build tab, click the More settings link to open the Project Settings dialog box. 3 On the All Settings tab, in the Advanced group, set Language to C or C++. Note: If you specify C++, MATLAB Coder wraps the C code into .cpp files so that you can use a C++ compiler and interface with external C++ applications. It does not generate C++ classes. Specifying a Language for Code Generation at the Command Line 1 Select a suitable compiler for your target language. 2 Create a configuration object for code generation. For example, for a library: cfg = coder.config('lib'); 3 Set the TargetLang property to 'C' or 'C++'. For example: cfg.TargetLang = 'C++'; Note: If you specify C++, MATLAB Coder wraps the C code into .cpp files. You can then use a C++ compiler and interface with external C++ applications. MATLAB Coder does not generate C++ classes. See Also • “Working with Configuration Objects” on page 19-27 • “Setting Up the C or C++ Compiler” Specify Data Type Used in Generated Code • “Specify Data Type in the Project Settings Dialog Box” on page 19-23 • “Specify Data Type at the Command Line” on page 19-23 MATLAB Coder can use built-in C data types or predefined types from rtwtypes.h in generated code. By default, the generated code uses built-in C types when declaring variables. 19-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Build Setting Configuration You can explicitly specify the data type used in generated code in the project settings dialog box or at the command line. Specify Data Type in the Project Settings Dialog Box 1 On the Build tab Settings pane, set the Output type to C/C++ Static Library, C/C++ Dynamic Library, or C/C++ Executable (depending on your requirements). 2 Click the More settings link to open the Project Settings dialog box. 3 To use built-in C types, on the Code Appearance tab, set Data Type Replacement to Use built-in C data types in the generated code. To use predefined types from rtwtypes.h, set Data Type Replacement to Use MathWorks typedefs in the generated code. Specify Data Type at the Command Line 1 Create a configuration object for code generation. Use coder.config with arguments 'lib','dll' or 'exe' (depending on your requirements). For example: cfg = coder.config('lib'); 2 To use built-in C types, set the DataTypeReplacement property to 'CBuiltIn'. cfg.DataTypeReplacement = 'CBuiltIn'; To use predefined types from rtwtypes.h, set the DataTypeReplacement property to 'CoderTypedefs'. Specify Output File Name Specify Output File Name in a Project On the project Build tab, in the Output file field, enter the file name. The file name can include an existing path. Note: Do not put spaces in the file name. By default, if the name of the first entry-point MATLAB file is fcn1, the output file name is: • fcn1 for C/C++ libraries and executables. 19-23 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code • fcn1_mex for MEX functions. By default, MATLAB Coder generates files in the folder project_folder/codegen/ target/fcn1: • project_folder is your current project folder • target is: • mex for MEX functions • lib for static C/C++ libraries • dll for dynamic C/C++ libraries • exe for C/C++ executables Command Line Alternative Use the codegen function -o option. Specify Output File Locations Specifying Output File Location in a Project The output file location should not contain: • Spaces, as this can lead to code generation failures in certain operating system configurations. • Non 7-bit ASCII characters, such as Japanese characters. 1 On the project Build tab, click More settings. 2 In the Project Settings dialog box, click the Paths tab. The default setting for the Build Folder field is A subfolder of the project folder. By default, MATLAB Coder generates files in the folder project_folder/ codegen/target/fcn1: • fcn1 is the name of the first entry-point file • target is: • mex for MEX functions • lib for static C/C++ libraries • dll for dynamically-linked C/C++ libraries 19-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Build Setting Configuration • exe for C/C++ executables 3 To change the output location, you can either: • Set Build Folder to A subfolder of the current MATLAB working folder MATLAB Coder generates files in the MATLAB_working_folder/codegen/ target/fcn1 folder • Set Build Folder to Specified folder. In the Build folder name field, provide the path to the folder. Command Line Alternative Use the codegen function -d option. Parameter Specification Methods If you are using... Use... Details A MATLAB Coder project The Project Settings dialog box “Specifying Build Configuration Parameters in the Project Settings Dialog Box” on page 19-26 codegen at the command line and want to specify a small number of parameters Configuration objects “Specifying Build Configuration Parameters at the Command Line Using Configuration Objects” on page 19-26 Configuration object dialog boxes “Specifying Build Configuration Parameters at the Command Line Using Dialog Boxes” on page 19-30 codegen in build scripts codegen at the command line and want to specify a large number of parameters Specify Build Configuration Parameters • “Specifying Build Configuration Parameters in the Project Settings Dialog Box” on page 19-26 • “Specifying Build Configuration Parameters at the Command Line Using Configuration Objects” on page 19-26 19-25 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code • “Specifying Build Configuration Parameters at the Command Line Using Dialog Boxes” on page 19-30 You can specify build configuration parameters from the MATLAB Coder project settings dialog box, the command line, or configuration object dialog boxes. Specifying Build Configuration Parameters in the Project Settings Dialog Box 1 On the MATLAB Coder project Build tab, click More settings. The Project Settings dialog box opens. This dialog box provides the set of configuration parameters applicable to the output type that you select. Note: MEX functions use a different set of configuration parameters than C/C++ libraries and executables. When you switch the output type between MEX Function or Instrumented MEX Function and C/C++ Static Library , C/C++ Dynamic Library or C/C++ Executable, verify these settings. For more information, see “Changing Output Type” on page 16-42. 2 Modify the parameters as required. For more information about parameters on a tab, click the Help button. Changes to the parameter settings take place immediately. 3 After specifying the build parameters, you can generate code by clicking the Build button on the same tab. Specifying Build Configuration Parameters at the Command Line Using Configuration Objects Types of Configuration Objects The codegen function uses configuration objects to customize your environment for code generation. The following table lists the available configuration objects. Configuration Object Description coder.CodeConfig If no Embedded Coder license is available or you disable use of the Embedded Coder license, specifies parameters for C/C++ library or executable generation. For more information, see the class reference information for coder.CodeConfig. 19-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Build Setting Configuration Configuration Object Description coder.EmbeddedCodeConfig If an Embedded Coder license is available, specifies parameters for C/C++ library or executable generation. For more information, see the class reference information for coder.EmbeddedCodeConfig. Specifies parameters of the target hardware implementation. If not specified, codegen generates code that is compatible with the MATLAB host computer. coder.HardwareImplementation For more information, see the class reference information for coder.HardwareImplementation. Specifies parameters for MEX code generation. coder.MexCodeConfig For more information, see the class reference information for coder.MexCodeConfig. Working with Configuration Objects To use configuration objects to customize your environment for code generation: 1 In the MATLAB workspace, define configuration object variables, as described in “Creating Configuration Objects” on page 19-28. For example, to generate a configuration object for C static library generation: cfg = coder.config('lib'); % Returns a coder.CodeConfig object if no % Embedded Coder license available. % Otherwise, returns a coder.EmbeddedCodeConfig object. 2 Modify the parameters of the configuration object as required, using one of these methods: • Interactive commands, as described in “Specifying Build Configuration Parameters at the Command Line Using Configuration Objects” on page 19-26 • Dialog boxes, as described in “Specifying Build Configuration Parameters at the Command Line Using Dialog Boxes” on page 19-30 3 Call the codegen function with the -config option. Specify the configuration object as its argument. 19-27 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code The -config option instructs codegen to generate code for the target, based on the configuration property values. In the following example, codegen generates a C static library from a MATLAB function, foo, based on the parameters of a code generation configuration object, cfg, defined in the first step: codegen -config cfg foo The -config option specifies the type of output that you want to build — in this case, a C static library. For more information, see codegen. Creating Configuration Objects You can define a configuration object in the MATLAB workspace. To Create... Use a Command Such As... MEX configuration object coder.MexCodeConfig cfg = coder.config('mex'); Code generation configuration object for generating a standalone C/C++ library or executable coder.CodeConfig % To generate a static library cfg = coder.config('lib'); % To generate a dynamic library cfg = coder.config('dll') % To generate an executable cfg = coder.config('exe'); Note: If an Embedded Coder license is available, creates a coder.EmbeddedCodeConfig object. If you use concurrent licenses, to disable check out of an Embedded Coder license, use one of the following commands: cfg = coder.config('lib', 'ecoder', false) cfg = coder.config('dll', 'ecoder', false) cfg = coder.config('exe', 'ecoder', false) Code generation configuration object for generating a standalone C/C++ library or executable for an embedded target % To generate a static library cfg = coder.config('lib'); % To generate a dynamic library cfg = coder.config('dll') 19-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Build Setting Configuration To Create... coder.EmbeddedCodeConfig Use a Command Such As... % To generate an executable cfg = coder.config('exe'); Note: Requires an Embedded Coder license; otherwise creates a coder.CodeConfig object. Hardware implementation hwcfg = coder.HardwareImplementation configuration object coder.HardwareImplementation Each configuration object comes with a set of parameters, initialized to default values. You can change these settings, as described in “Modifying Configuration Objects at the Command Line Using Dot Notation” on page 19-29. Modifying Configuration Objects at the Command Line Using Dot Notation You can use dot notation to modify the value of one configuration object parameter at a time. Use this syntax: configuration_object.property = value Dot notation uses assignment statements to modify configuration object properties: • To specify a main function during C/C++ code generation: cfg = coder.config('exe'); cfg.CustomInclude = 'c:\myfiles'; cfg.CustomSource = 'main.c'; codegen -config cfg foo • To automatically generate and launch code generation reports after generating a C/C+ + static library: cfg = coder.config('lib'); cfg.GenerateReport= true; cfg.LaunchReport = true; codegen -config cfg foo Saving Configuration Objects Configuration objects do not automatically persist between MATLAB sessions. Use one of the following methods to preserve your settings: 19-29 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Save a configuration object to a MAT-file and then load the MAT-file at your next session For example, assume you create and customize a MEX configuration object mexcfg in the MATLAB workspace. To save the configuration object, at the MATLAB prompt, enter: save mexcfg.mat mexcfg The save command saves mexcfg to the file mexcfg.mat in the current folder. To restore mexcfg in a new MATLAB session, at the MATLAB prompt, enter: load mexcfg.mat The load command loads the objects defined in mexcfg.mat to the MATLAB workspace. Write a script that creates the configuration object and sets its properties. You can rerun the script whenever you need to use the configuration object again. Specifying Build Configuration Parameters at the Command Line Using Dialog Boxes 1 Create a configuration object as described in “Creating Configuration Objects” on page 19-28. For example, to create a coder.MexCodeConfig configuration object for MEX code generation: mexcfg = coder.config('mex'); 2 Open the property dialog box using one of these methods: • In the MATLAB workspace, double-click the configuration object variable. • At the MATLAB prompt, issue the open command, passing it the configuration object variable, as in this example: open mexcfg 3 In the dialog box, modify configuration parameters as required, then click Apply. 4 Call the codegen function with the -config option. Specify the configuration object as its argument: 19-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Write a script that creates the configuration object and sets its properties. codegen -config mexcfg foo The -config option specifies the type of output that you want to build. For more information, see codegen. 19-31 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Standard Math Libraries By default, the MATLAB Coder software generates code that calls the C89/C90 (ANSI C) library for math operations. Depending on your language choice, you have the option of changing the standard math library that the code generation software uses. Available libraries include: Library Name Language Support Standard C89/C90 (ANSI) C, C++ ANSI C89/C90 (default) C99 (ISO) C, C++ ISO/IEC 9899:1990 C++03 (ISO) C++ ISO/IEC 14882:2003 19-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Change the Standard Math Library Change the Standard Math Library By default, the MATLAB Coder software uses the ANSI C89/C90 C math library when generating C or C++ code. If your compiler supports newer language standards, you can specify a different supported library. To change the library: • In a project, on the Hardware tab, set the Standard Math Library parameter. • In a code configuration object, set the TargetLangStandard parameter. See Also • “Standard Math Libraries” on page 19-32 • “Specifying Build Configuration Parameters in the Project Settings Dialog Box” on page 19-26 • “Specifying Build Configuration Parameters at the Command Line Using Configuration Objects” on page 19-26 19-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Share Build Configuration Settings To share build configuration settings between multiple projects or between the project and command-line workflow, use the project Export settings and Import settings options. Export Settings To export the current project settings to a code generation configuration object stored in the base workspace: 1 In the top right corner of the project, click the Actions icon ( ) and select Export settings. 2 In the Export Project Settings dialog box, specify a name for the configuration object. MATLAB Coder saves the project settings information in a configuration object with the specified name in the base workspace. Project Output Type Configuration Object MEX Function coder.MexCodeConfig 19-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Share Build Configuration Settings Project Output Type Configuration Object Instrumented MEX Function C/C++ Static Library C/C++ Dynamic Library C/C++ Executable Without an Embedded Coder license: coder.CodeConfig With an Embedded Coder license: coder.EmbeddedCodeConfig You can then either import these settings into another project or use it with the codegen function -config option to generate code at the command line. Import Settings To import the settings saved in a code generation configuration object stored in the base workspace: 1 In the top right corner of the project, click the Actions icon ( ) and select Import settings. 2 In the Import Project Settings dialog box, select the configuration object that you want to use. MATLAB Coder imports the settings saved in the configuration object and uses them as the current project settings. 19-35 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Note: When you import a coder.MexCodeConfig object, if the project output type is not already set to Instrumented MEX Function, the output type is set to MEX Function. See Also • “Build Setting Configuration” on page 19-19 • coder.config • “Convert MATLAB Coder Project to MATLAB Script” on page 19-37 19-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert MATLAB Coder Project to MATLAB Script Convert MATLAB Coder Project to MATLAB Script You can convert a MATLAB Coder project to the equivalent script of MATLAB commands. The script reproduces the project in a configuration object and runs the codegen command. You can: • Move from a project workflow to a command-line workflow. • Save the project as a text file that you can share. 1 Suppose that the project file, myproject.prj, is on the search path. Convert myproject to the script named myscript.m. coder -tocode myproject -script myscript.m 2 3 myscript.m appears in the current working folder . If a file with the name myscript.m exists, the coder command overwrites it. If you omit the -script option, the coder command writes the script to the Command Window. Make sure that the entry-point functions that are arguments to codegen in the script are on the search path. Run the script. myscript The following variables appear in the base workspace. cfg configuration object ARGS types of input arguments, if the project has entry-point function inputs GLOBALS initial values of global data, if the project has global data cfg, ARGS, and GLOBALS appear in the workspace only after you run the script. The type of configuration object depends on the project output type. Project Output Type Configuration Object MEX Function coder.MexCodeConfig C/C++ Static Library Without an Embedded Coder license: coder.CodeConfig C/C++ Dynamic Library C/C++ Executable 19-37 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Project Output Type Configuration Object With an Embedded Coder license: coder.EmbeddedCodeConfig You can import the settings from the configuration object cfg into a project. See “Share Build Configuration Settings” on page 19-34. If a project includes automated fixed-point conversion, the -tocode option of the coder command generates a pair of scripts for fixed-point conversion and fixed-point code generation. For an example, see “Convert Fixed-Point Conversion Project to MATLAB Scripts”. See Also coder 19-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Primary Function Input Specification Primary Function Input Specification In this section... “Why You Must Specify Input Properties” on page 19-39 “Properties to Specify” on page 19-39 “Rules for Specifying Properties of Primary Inputs” on page 19-42 “Methods for Defining Properties of Primary Inputs” on page 19-43 “Define Input Properties by Example at the Command Line” on page 19-44 “Specify Constant Inputs at the Command Line” on page 19-46 “Specify Variable-Size Inputs at the Command Line” on page 19-47 Why You Must Specify Input Properties Because C and C++ are statically typed languages, MATLAB Coder must determine the properties of all variables in the MATLAB files at compile time. To infer variable properties in MATLAB files, MATLAB Coder must be able to identify the properties of the inputs to the primary function, also known as the top-level or entry-point function. Therefore, if your primary function has inputs, you must specify the properties of these inputs, to MATLAB Coder. If your primary function has no input parameters, MATLAB Coder can compile your MATLAB file without modification. You do not need to specify properties of inputs to local functions or external functions called by the primary function. If you use the tilde (~) character to specify unused function inputs: • In MATLAB Coder projects, if you want a different type to appear in the generated code, specify the type. Otherwise, the inputs default to real, scalar doubles. • When generating code with codegen, you must specify the type of these inputs using the -args option. Properties to Specify If your primary function has inputs, you must specify the following properties for each input. For... Specify properties... Class Size Complexity numerictype fimath 19-39 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code For... Specify properties... Fixed-point inputs Each field in a structure input Specify properties for each field according to its class When a primary input is a structure, the code generation software treats each field as a separate input. Therefore, you must specify properties for allfields of a primary structure input in the order that they appear in the structure definition: • For each field of input structures, specify class, size, and complexity. • For each field that is fixed-point class, also specify numerictype, and fimath. Other inputs Default Property Values MATLAB Coder assigns the following default values for properties of primary function inputs. Property Default class double size scalar complexity real numerictype No default fimath MATLAB default fimath object Specifying Default Values for Structure Fields In most cases, when you don't explicitly specify values for properties, MATLAB Coder uses defaults except for structure fields. The only way to name a field in a structure is to set at least one of its properties. Therefore, you might need to specify default values for properties of structure fields. For examples, see “Specifying Class and Size of Scalar Structure” and “Specifying Class and Size of Structure Array”. Specifying Default fimath Values for MEX Functions MEX functions generated with MATLAB Coder use the default fimath value in effect at compile time. If you do not specify a default fimath value, MATLAB Coder uses the MATLAB default fimath. The MATLAB factory default has the following properties: 19-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify properties for each field according to its class RoundingMethod: Nearest OverflowAction: Saturate ProductMode: FullPrecision SumMode: FullPrecision CastBeforeSum: true For more information, see “fimath for Sharing Arithmetic Rules”. When running MEX functions that depend on the default fimath value, do not change this value during your MATLAB session. Otherwise, you receive a run-time warning, alerting you to a mismatch between the compile-time and run-time fimath values. For example, suppose you define the following MATLAB function test: function y = test %#codegen y = fi(0); The function test constructs a fi object without explicitly specifying a fimath object. Therefore, test relies on the default fimath object in effect at compile time. At the MATLAB prompt, generate the MEX function text_mex to use the factory setting of the MATLAB default fimath: codegen test % codegen generates a MEX function, test_mex, % in the current folder Next, run test_mex to display the MATLAB default fimath value: test_mex ans = 0 DataTypeMode: Signedness: WordLength: FractionLength: Fixed-point: binary point scaling Signed 16 15 Now create a local MATLAB fimath value. so you no longer use the default setting: F = fimath('RoundingMethod','Floor'); Finally, clear the MEX function from memory and rerun it: clear test_mex test_mex 19-41 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code The mismatch is detected and causes an error: ??? This function was generated with a different default fimath than the current default. Error in ==> test_mex Supported Classes The following table presents the class names supported by MATLAB Coder. Class Name Description logical Logical array of true and false values char Character array int8 8-bit signed integer array uint8 8-bit unsigned integer array int16 16-bit signed integer array uint16 16-bit unsigned integer array int32 32-bit signed integer array uint32 32-bit unsigned integer array int64 64-bit signed integer array uint64 64–bit unsigned integer array single Single-precision floating-point or fixed-point number array double Double-precision floating-point or fixed-point number array struct Structure array embedded.fi Fixed-point number array Rules for Specifying Properties of Primary Inputs When specifying the properties of primary inputs, follow these rules. • You must specify the class of all primary inputs. If you do not specify the size or complexity of primary inputs, they default to real scalars. 19-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify properties for each field according to its class • For each primary function input whose class is fixed point (fi), you must specify the input numerictype and fimath properties. • For each primary function input whose class is struct, you must specify the properties of each of its fields in the order that they appear in the structure definition. Methods for Defining Properties of Primary Inputs Method Advantages Disadvantages “Specifying Properties • If you are working in a MATLAB • Not efficient for specifying of Primary Function Coder project, easy to use memory-intensive inputs such as Inputs in a Project” large structures and arrays • Does not alter original MATLAB code • MATLAB Coder saves the definitions in the project file “Define Input • Easy to use • Must be specified at the Properties by Example • Does not alter original MATLAB command line every time you at the Command Line” invoke codegen (unless you use code on page 19-44 a script) • Designed for prototyping a function that has a small number • Not efficient for specifying memory-intensive inputs such as of primary inputs Note: If you define large structures and arrays input properties programmatically in the MATLAB file, you cannot use this method “Define Input Properties Programmatically in the MATLAB File” • Integrated with MATLAB code; no need to redefine properties each time you invoke MATLAB Coder • Provides documentation of property specifications in the MATLAB code • Uses complex syntax • MATLAB Coder project files do not currently recognize properties defined programmatically. If you are using a project, you must reenter the input types in the project. • Efficient for specifying memoryintensive inputs such as large structures 19-43 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Define Input Properties by Example at the Command Line • “Command Line Option -args” on page 19-44 • “Rules for Using the -args Option” on page 19-44 • “Specifying Properties of Primary Inputs by Example at the Command Line” on page 19-45 • “Specifying Properties of Primary Fixed-Point Inputs by Example at the Command Line” on page 19-45 Command Line Option -args The codegen function provides a command-line option -args for specifying the properties of primary (entry-point) function inputs as a cell array of example values. The cell array can be a variable or literal array of constant values. Using this option, you specify the properties of inputs at the same time as you generate code for the MATLAB function with codegen . If you have a test function or script that calls the entry-point MATLAB function with the required types, you can use coder.getArgTypes to determine the types of the function inputs. coder.getArgTypes returns a cell array of coder.Type objects that you can pass to codegen using the -args option. See “Specifying General Properties of Primary Inputs” for codegen. Rules for Using the -args Option When using the -args command-line option to define properties by example, follow these rules: • The cell array of sample values must contain the same number of elements as primary function inputs. • The order of elements in the cell array must correspond to the order in which inputs appear in the primary function signature — for example, the first element in the cell array defines the properties of the first primary function input. Note: If you specify an empty cell array with the -args option, codegen interprets this to mean that the function takes no inputs; a compile-time error occurs if the function does have inputs. 19-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify properties for each field according to its class Specifying Properties of Primary Inputs by Example at the Command Line Consider a MATLAB function that adds its two inputs: function y = mcf(u,v) %#codegen y = u + v; The following examples show how to specify different properties of the primary inputs u and v by example at the command line: • Use a literal cell array of constants to specify that both inputs are real scalar doubles: codegen mcf -args {0,0} • Use a literal cell array of constants to specify that input u is an unsigned 16-bit, 1by-4 vector and input v is a scalar double: codegen mcf -args {zeros(1,4,'uint16'),0} • Assign sample values to a cell array variable to specify that both inputs are real, unsigned 8-bit integer vectors: a = uint8([1;2;3;4]) b = uint8([5;6;7;8]) ex = {a,b} codegen mcf -args ex Specifying Properties of Primary Fixed-Point Inputs by Example at the Command Line To generate a MEX function or C/C++ code for fixed-point MATLAB code, you must install Fixed-Point Designer software. Consider a MATLAB function that calculates the square root of a fixed-point number: %#codegen function y = sqrtfi(x) y = sqrt(x); To specify the properties of the primary fixed-point input x by example, follow these steps: 1 Define the numerictype properties for x, for example: T = numerictype('WordLength',32,... 19-45 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code 'FractionLength',23,... 'Signed',true); 2 Define the fimath properties for x, for example: F = fimath('SumMode','SpecifyPrecision',... 'SumWordLength',32,... 'SumFractionLength',23,... 'ProductMode','SpecifyPrecision',... 'ProductWordLength',32,... 'ProductFractionLength',23); 3 Create a fixed-point variable with the numerictype and fimath properties that you just defined, for example: myeg = { fi(4.0,T,F) }; 4 Compile the function sqrtfi using the codegen command, passing the variable myeg as the argument to the -args option, for example: codegen sqrtfi -args myeg; Specify Constant Inputs at the Command Line If you know that your primary inputs will not change at run time, you can reduce overhead in the generated code by specifying that the primary inputs are constant values. Constant inputs are commonly used for flags that control how an algorithm executes and values that specify the sizes or types of data. To specify that inputs are constants, use the -args command-line option with a coder.Constant object. To specify that an input is a constant with the size, class, complexity, and value of constant_input, use the following syntax: -args {coder.Constant(constant_input)} Calling Functions with Constant Inputs The code generation software compiles constant function inputs into the generated code. In the generated C or C++ code, function signatures do not contain the constant inputs. By default, MEX function signatures contain the constant inputs. When you call a MEX function, you must provide the compile-time constant values. The constant input values must match the compile-time values. You can control whether a MEX function signature includes constant inputs and whether the constant input values must match the compiletime values. See “Control Constant Inputs in MEX Function Signatures”. 19-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify properties for each field according to its class Specifying a Structure as a Constant Input Suppose you define a structure tmp in the MATLAB workspace to specify the dimensions of a matrix: tmp = struct('rows', 2, 'cols', 3); The following MATLAB function rowcol accepts a structure input p to define matrix y: function y = rowcol(u,p) %#codegen y = zeros(p.rows,p.cols) + u; The following example shows how to specify that primary input u is a double scalar variable and primary input p is a constant structure: codegen rowcol -args {0,coder.Constant(tmp)} Specify Variable-Size Inputs at the Command Line Variable-size data is data whose size might change at run time. MATLAB supports bounded and unbounded variable-size data for code generation. Bounded variablesize data has fixed upper bounds. This data can be allocated statically on the stack or dynamically on the heap. Unbounded variable-size data does not have fixed upper bounds. This data must be allocated on the heap. You can define inputs to have one or more variable-size dimensions — and specify their upper bounds — using the -args option and coder.typeof function: -args {coder.typeof(example_value, size_vector, variable_dims} Specifies a variable-size input with: • Same class and complexity as example_value • Same size and upper bounds as size_vector • Variable dimensions specified by variable_dims When you enable dynamic memory allocation, you can specify Inf in the size vector for dimensions with unknown upper bounds at compile time. When variable_dims is a scalar, it is applied to all the dimensions, with the following exceptions: • If the dimension is 1 or 0, which are fixed. • If the dimension is unbounded, which is always variable size. 19-47 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code For more information, see coder.typeof and “Generate Code for Variable-Size Data”. Specifying a Variable-Size Vector Input 1 Write a function that computes the average of every n elements of a vector A and stores them in a vector B: function B = nway(A,n) %#codegen % Compute average of every N elements of A and put them in B. coder.extrinsic('error'); if ((mod(numel(A),n) == 0) && (n>=1 && n<=numel(A))) B = ones(1,numel(A)/n); k = 1; for i = 1 : numel(A)/n B(i) = mean(A(k + (0:n-1))); k = k + n; end else B = zeros(1,0); error('n <= 0 or does not divide number of elements evenly'); end 2 Specify the first input A as a vector of double values. Its first dimension stays fixed in size and its second dimension can grow to an upper bound of 100. Specify the second input n as a double scalar. codegen -report nway -args {coder.typeof(0,[1 100],1),1} 3 As an alternative, assign the coder.typeof expression to a MATLAB variable, then pass the variable as an argument to -args: vareg = coder.typeof(0,[1 100],1) codegen -report nway -args {vareg, 0} 19-48 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Control Constant Inputs in MEX Function Signatures Control Constant Inputs in MEX Function Signatures In this section... “Control MEX Function Signature Using the Project Interface” on page 19-49 “Control MEX Function Signature at the Command-Line Interface” on page 19-49 “Options for Controlling Constant Inputs in MEX Function Signatures” on page 19-49 “Call MEX Function with a Constant Input” on page 19-51 “See Also” on page 19-52 You can control whether a generated MEX function signature includes constant inputs. If you want to use the same test file to run the original MATLAB function and the MEX function, then the MEX function signature must contain the constant inputs. You can also control whether the run-time values of the constant inputs must match the compiletime values. Checking that the values match can slow down execution speed. Control MEX Function Signature Using the Project Interface 1 2 On the Build tab Settings pane, set Output type to MEX Function. On the Project Settings dialog box All Settings tab, set Constant Inputs to one of the menu options. See “Options for Controlling Constant Inputs in MEX Function Signatures” on page 19-49. Control MEX Function Signature at the Command-Line Interface 1 Create a code configuration object for MEX code generation. 2 Set the ConstantInputs parameter to 'CheckValues', 'IgnoreValues', or 'Remove' For example: mexcfg = coder.config('mex'); mexcfg.ConstantInputs = 'IgnoreValues'; For a description of the options, see “Options for Controlling Constant Inputs in MEX Function Signatures” on page 19-49 Options for Controlling Constant Inputs in MEX Function Signatures The following table lists the options for the: 19-49 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code • Constant Inputs setting in a project with Output Type set to MEX. • ConstantInputs property in a configuration object for MEX code generation. Constant Inputs (Project) ConstantInputs (Configuration Object) Check values at run time 'CheckValues' (default) Description • The MEX function signature includes the constant inputs. When you call the function, you must provide the constant inputs. • The run-time values of the constant inputs must match the compile-time values. When you call the function, you must provide the value that was used at compiletime. • Allows you to use the same test file to run the original MATLAB algorithm and the MEX function. • Slows down execution of the MEX function. • This setting is the default. Ignore input value 'IgnoreValues' • The MEX function signature includes the constant inputs. When you call the function, you must provide the constant inputs. • The run-time values of the constant inputs can differ from the compile-time values. • Allows you to use the same test file to run the original MATLAB algorithm and the MEX function. 19-50 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Control Constant Inputs in MEX Function Signatures Constant Inputs (Project) ConstantInputs (Configuration Object) Description Remove from MEX signature 'Remove' The MEX function signature does not include the constant inputs. When you call the function, you do not provide the constant inputs. Call MEX Function with a Constant Input This example shows how to call MEX functions that have constant inputs. It shows how to use the ConstantInputs parameter to control whether the MEX function signature includes constant inputs and whether the constant input values must match the compiletime values. Write a function identity that copies its input to its output. function y = identity(u) %#codegen y = u; Create a code configuration object for MEX code generation. cfg = coder.config('mex'); Generate a MEX function identity_mex with the constant input 42. codegen identity -config cfg -args {coder.Constant(42)} Call identity_mex. You must provide the input 42. identity_mex(42) ans = 42 Configure ConstantInputs so that the MEX function does not check that the input value matches the compile-time value. cfg.ConstantInputs = 'IgnoreValues'; Generate identity_mex with the new configuration. 19-51 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code codegen identity -config cfg -args {coder.Constant(42)} Call identity_mex with a constant input value other than 42 . identity_mex(50) ans = 42 The MEX function ignored the input value 50. Configure ConstantInputs so that the MEX function does not include the constant input. cfg.ConstantInputs = 'Remove'; Generate identity_mex with the new configuration. codegen identity -config cfg -args {coder.Constant(42)} Call identity_mex. Do not provide the input value . identity_mex() ans = 42 See Also • “Specify Constant Inputs at the Command Line” • “Define Constant Input Parameters in a Project” 19-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Properties Programmatically in the MATLAB File Define Input Properties Programmatically in the MATLAB File With MATLAB Coder, you use the MATLAB assert function to define properties of primary function inputs directly in your MATLAB file. In this section... “How to Use assert with MATLAB Coder” on page 19-53 “Rules for Using assert Function” on page 19-59 “Specifying General Properties of Primary Inputs” on page 19-59 “Specifying Properties of Primary Fixed-Point Inputs” on page 19-60 “Specifying Class and Size of Scalar Structure” on page 19-61 “Specifying Class and Size of Structure Array” on page 19-62 How to Use assert with MATLAB Coder Use the assert function to invoke standard MATLAB functions for specifying the class, size, and complexity of primary function inputs. You must use one of the following methods when specifying input properties using the assert function. Use the exact syntax that is provided; do not modify it. • “Specify Any Class” on page 19-54 • “Specify fi Class” on page 19-54 • “Specify Structure Class” on page 19-55 • “Specify Fixed Size” on page 19-55 • “Specify Scalar Size” on page 19-55 • “Specify Upper Bounds for Variable-Size Inputs” on page 19-56 • “Specify Inputs with Fixed- and Variable-Size Dimensions” on page 19-56 • “Specify Size of Individual Dimensions” on page 19-56 • “Specify Real Input” on page 19-57 • “Specify Complex Input” on page 19-57 • “Specify numerictype of Fixed-Point Input” on page 19-57 • “Specify fimath of Fixed-Point Input” on page 19-58 19-53 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code • “Specify Multiple Properties of Input” on page 19-58 Specify Any Class assert ( isa ( param, 'class_name') ) Sets the input parameter param to the MATLAB class class_name. For example, to set the class of input U to a 32-bit signed integer, call: ... assert(isa(U,'int32')); ... If you set the class of an input parameter to fi, you must also set its numerictype, see “Specify numerictype of Fixed-Point Input” on page 19-57. You can also set its fimath properties, see “Specify fimath of Fixed-Point Input” on page 19-58. If you do not set the fimath properties, codegen uses the MATLAB default fimath value. If you set the class of an input parameter to struct, you must specify the properties of all fields in the order that they appear in the structure definition. Specify fi Class assert ( isfi ( param ) ) assert ( isa ( param, 'embedded.fi' ) ) Sets the input parameter param to the MATLAB class fi (fixed-point numeric object). For example, to set the class of input U to fi, call: ... assert(isfi(U)); ... or ... assert(isa(U,'embedded.fi')); ... If you set the class of an input parameter to fi, you must also set its numerictype, see “Specify numerictype of Fixed-Point Input” on page 19-57. You can also set its fimath properties, see “Specify fimath of Fixed-Point Input” on page 19-58. If you do not set the fimath properties, codegen uses the MATLAB default fimath value. 19-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Properties Programmatically in the MATLAB File Specify Structure Class assert ( isstruct ( param ) ) assert ( isa ( param, 'struct' ) ) Sets the input parameter param to the MATLAB class struct (structure). For example, to set the class of input U to a struct, call: ... assert(isstruct(U)); ... or ... assert(isa(U, 'struct')); ... If you set the class of an input parameter to struct, you must specify the properties of all fields in the order they appear in the structure definition. Specify Fixed Size assert ( all ( size (param) == [dims ] ) ) Sets the input parameter param to the size specified by dimensions dims. For example, to set the size of input U to a 3-by-2 matrix, call: ... assert(all(size(U)== [3 2])); ... Specify Scalar Size assert ( isscalar (param ) ) assert ( all ( size (param) == [ 1 ] ) ) Sets the size of input parameter param to scalar. To set the size of input U to scalar, call: ... assert(isscalar(U)); ... or ... 19-55 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code assert(all(size(U)== [1])); ... Specify Upper Bounds for Variable-Size Inputs assert ( all(size(param)<=[N0 N1 ...])); assert ( all(size(param)<[N0 N1 ...])); Sets the upper-bound size of each dimension of input parameter param. To set the upperbound size of input U to be less than or equal to a 3-by-2 matrix, call: assert(all(size(U)<=[3 2])); Note: You can also specify upper bounds for variable-size inputs using coder.varsize. Specify Inputs with Fixed- and Variable-Size Dimensions assert ( all(size(param)>=[M0 M1 ...])); assert ( all(size(param)<=[N0 N1 ...])); When you use assert(all(size(param)>=[M0 M1 ...])) to specify the lower-bound size of each dimension of an input parameter: • You must also specify an upper-bound size for each dimension of the input parameter. • For each dimension, k, the lower-bound Mk must be less than or equal to the upperbound Nk. • To specify a fixed-size dimension, set the lower and upper bound of a dimension to the same value. • Bounds must be non-negative. To fix the size of the first dimension of input U to 3 and set the second dimension as variable size with upper-bound of 2, call: assert(all(size(U)>=[3 0])); assert(all(size(U)<=[3 2])); Specify Size of Individual Dimensions assert (size(param, k)==Nk); assert (size(param, k)<=Nk); assert (size(param, k)<Nk); 19-56 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Properties Programmatically in the MATLAB File You can specify individual dimensions as well as specifying all dimensions simultaneously or instead of specifying all dimensions simultaneously. The following rules apply: • You must specify the size of each dimension at least once. • The last dimension specification takes precedence over earlier specifications. Sets the upper-bound size of dimension k of input parameter param. To set the upperbound size of the first dimension of input U to 3, call: assert(size(U,1)<=3) To fix the size of the second dimension of input U to 2, call: assert(size(U,2)==2) Specify Real Input assert ( isreal (param ) ) Specifies that the input parameter param is real. To specify that input U is real, call: ... assert(isreal(U)); ... Specify Complex Input assert ( ~isreal (param ) ) Specifies that the input parameter param is complex. To specify that input U is complex, call: ... assert(~isreal(U)); ... Specify numerictype of Fixed-Point Input assert ( isequal ( numerictype ( fiparam ), T ) ) Sets the numerictype properties of fi input parameter fiparam to the numerictype object T. For example, to specify the numerictype property of fixed-point input U as a signed numerictype object T with 32-bit word length and 30-bit fraction length, use the following code: 19-57 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code %#codegen ... % Define the numerictype object. T = numerictype(1, 32, 30); % Set the numerictype property of input U to T. assert(isequal(numerictype(U),T)); ... Specify fimath of Fixed-Point Input assert ( isequal ( fimath ( fiparam ), F ) ) Sets the fimath properties of fi input parameter fiparam to the fimath object F. For example, to specify the fimath property of fixed-point input U so that it saturates on integer overflow, use the following code: %#codegen ... % Define the fimath object. F = fimath('OverflowMode','saturate'); % Set the fimath property of input U to F. assert(isequal(fimath(U),F)); ... If you do not specify the fimath properties using assert, codegen uses the MATLAB default fimath value. Specify Multiple Properties of Input assert ( function1 ( params ) && function2 ( params ) && function3 ( params ) && ... ) Specifies the class, size, and complexity of one or more inputs using a single assert function call. For example, the following code specifies that input U is a double, complex, 3-by-3 matrix, and input V is a 16-bit unsigned integer: %#codegen ... assert(isa(U,'double') && ~isreal(U) && all(size(U) == [3 3]) && isa(V,'uint16')); ... 19-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Properties Programmatically in the MATLAB File Rules for Using assert Function When using the assert function to specify the properties of primary function inputs, follow these rules: • Call assert functions at the beginning of the primary function, before control-flow operations such as if statements or subroutine calls. • Do not call assert functions inside conditional constructs, such as if, for, while, and switch statements. • Use the assert function with MATLAB Coder only for specifying properties of primary function inputs before converting your MATLAB code to C/C++ code. • If you set the class of an input parameter to fi, you must also set its numerictype. See “Specify numerictype of Fixed-Point Input” on page 19-57. You can also set its fimath properties. See “Specify fimath of Fixed-Point Input” on page 19-58. If you do not set the fimath properties, codegen uses the MATLAB default fimath value. • If you set the class of an input parameter to struct, you must specify the class, size, and complexity of all fields in the order that they appear in the structure definition. • When you use assert(all(size(param)>=[M0 M1 ...])) to specify the lowerbound size of each dimension of an input parameter: • You must also specify an upper-bound size for each dimension of the input parameter. • For each dimension, k, the lower-bound Mk must be less than or equal to the upper-bound Nk. • To specify a fixed-size dimension, set the lower and upper bound of a dimension to the same value. • Bounds must be non-negative. • If you specify individual dimensions, the following rules apply: • You must specify the size of each dimension at least once. • The last dimension specification takes precedence over earlier specifications. Specifying General Properties of Primary Inputs In the following code excerpt, a primary MATLAB function mcspecgram takes two inputs: pennywhistle and win. The code specifies the following properties for these inputs: 19-59 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Input Property Value pennywhistle class int16 size 220500-by-1 vector complexity real (by default) class double size 1024-by-1 vector complexity real (by default) win %#codegen function y = mcspecgram(pennywhistle,win) nx = 220500; nfft = 1024; assert(isa(pennywhistle,'int16')); assert(all(size(pennywhistle) == [nx 1])); assert(isa(win, 'double')); assert(all(size(win) == [nfft 1])); ... Alternatively, you can combine property specifications for one or more inputs inside assert commands: %#codegen function y = mcspecgram(pennywhistle,win) nx = 220500; nfft = 1024; assert(isa(pennywhistle,'int16') && all(size(pennywhistle) == [nx 1])); assert(isa(win, 'double') && all(size(win) == [nfft 1])); ... Specifying Properties of Primary Fixed-Point Inputs To specify fixed-point inputs, you must install Fixed-Point Designer software. In the following example, the primary MATLAB function mcsqrtfi takes one fixed-point input x. The code specifies the following properties for this input. Property Value class fi 19-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Input Properties Programmatically in the MATLAB File Property Value numerictype numerictype object T, as specified in the primary function fimath fimath object F, as specified in the primary function size scalar complexity real (by default) function y = mcsqrtfi(x) %#codegen T = numerictype('WordLength',32,'FractionLength',23,... 'Signed',true); F = fimath('SumMode','SpecifyPrecision',... 'SumWordLength',32,'SumFractionLength',23,... 'ProductMode','SpecifyPrecision',... 'ProductWordLength',32,'ProductFractionLength',23); assert(isfi(x)); assert(isequal(numerictype(x),T)); assert(isequal(fimath(x),F)); y = sqrt(x); Specifying Class and Size of Scalar Structure Assume you have defined S as the following scalar MATLAB structure: S = struct('r',double(1),'i',int8(4)); Here is code that specifies the class and size of S and its fields when passed as an input to your MATLAB function: function y = fcn(S) %#codegen % Specify the class of the input as struct. assert(isstruct(S)); % Specify the class and size of the fields r and i % in the order in which you defined them. assert(isa(S.r,'double')); assert(isa(S.i,'int8'); ... In most cases, when you don't explicitly specify values for properties, MATLAB Coder uses defaults — except for structure fields. The only way to name a field in a structure 19-61 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code is to set at least one of its properties. As a minimum, you must specify the class of a structure field Specifying Class and Size of Structure Array For structure arrays, you must choose a representative element of the array for specifying the properties of each field. For example, assume you have defined S as the following 1-by-2 array of MATLAB structures: S = struct('r',{double(1), double(2)},'i',{int8(4), int8(5)}); The following code specifies the class and size of each field of structure input S using the first element of the array: %#codegen function y = fcn(S) % Specify the class of the input S as struct. assert(isstruct(S)); % Specify the size of the fields r and i % based on the first element of the array. assert(all(size(S) == [1 2])); assert(isa(S(1).r,'double')); assert(isa(S(1).i,'int8')); The only way to name a field in a structure is to set at least one of its properties. As a minimum, you must specify the class of all fields. 19-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Speed Up Compilation Speed Up Compilation In this section... “Generate Code Only” on page 19-63 “Disable Compiler Optimization” on page 19-63 Generate Code Only If you select this option, MATLAB Coder does not invoke the make command or generate compiled object code. When you want to iterate rapidly between modifying MATLAB code and generating C/C++ code and you want to inspect the generated code, this option saves you time during the development cycle . In the Project Interface On the project Build tab, select Generate code only. At the Command Line Use the codegen -c option to only generate code without invoking the make command. For example, to generate code only for a function, foo, that takes one single, scalar input: codegen -c foo -args {single(0)} For more information and a complete list of compilation options, see codegen. Disable Compiler Optimization Turning compiler optimizations off shortens compile time, but increases run time. In the Project Interface 1 On the MATLAB Coder project Build tab, verify that the Output type is C/C++ Static Library, C/C++ Dynamic Library or C/C++ Executable. 2 On the Build tab, click the More settings link. 3 In the Project Settings dialog box All Settings tab, under Advanced, set Compiler optimization level to Off. 19-63 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code At the Command Line 1 Create a code generation configuration object for C/C++ library or executable. For example, for a static library: cfg = coder.config('lib'); 2 Set the CCompilerOptimization to Off. cfg.CCompilerOptimization='Off'; 19-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Paths and File Infrastructure Setup Paths and File Infrastructure Setup In this section... “Compile Path Search Order” on page 19-65 “Specifying Folders to Search for Custom Code” on page 19-65 “Naming Conventions” on page 19-66 Compile Path Search Order MATLAB Coder resolves MATLAB functions by searching first on the code generation path and then on the MATLAB path. The code generation path contains the current folder and the code generation libraries. By default, unless MATLAB Coder determines that a function should be extrinsic or you explicitly declare the function to be extrinsic, MATLAB Coder tries to compile and generate code for functions it finds on the path. MATLAB Coder does not compile extrinsic functions, but rather dispatches them to the MATLAB interpreter for execution. See “Resolution of Function Calls for Code Generation”. Specifying Folders to Search for Custom Code If you want to integrate custom code — such as source, header, and library files — with the generated code, you can specify additional folder to search. The following table describes how to specify these search paths. The path should not contain spaces, as this can lead to code generation failures in certain operating system configurations. If the path contains non 7-bit ASCII characters, such as Japanese characters, MATLAB Coder might not be able to find files on this path. To specify additional folders: Do this: Using the MATLAB Coder interface On the MATLAB Coder project Build tab: At the command line 1 Click the More settings link. 2 In the Project Settings dialog box, click the Paths tab. 3 For the Search paths field, either browse to add a folder to the search path or enter the full path. The search path must not contain spaces. Use the codegen function -I option. 19-65 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Naming Conventions MATLAB Coder enforces naming conventions for MATLAB functions and generated files. • “Reserved Prefixes” on page 19-66 • “Reserved Keywords” on page 19-66 • “Conventions for Naming Generated files” on page 19-69 Reserved Prefixes MATLAB Coder reserves the prefix eml for global C/C++ functions and variables in generated code. For example, MATLAB for code generation run-time library function names begin with the prefix emlrt, such as emlrtCallMATLAB. To avoid naming conflicts, do not name C/C++ functions or primary MATLAB functions with the prefix eml. Reserved Keywords • “C Reserved Keywords” on page 19-66 • “C++ Reserved Keywords” on page 19-67 • “Reserved Keywords for Code Generation” on page 19-67 • “MATLAB Coder Code Replacement Library Keywords” on page 19-68 MATLAB Coder software reserves certain words for its own use as keywords of the generated code language. MATLAB Coder keywords are reserved for use internal to MATLAB Coder software and should not be used in MATLAB code as identifiers or function names. C reserved keywords should also not be used in MATLAB code as identifiers or function names. If your MATLAB code contains reserved keywords, the code generation build does not complete and an error message is displayed. To address this error, modify your code to use identifiers or names that are not reserved. If you are generating C++ code using the MATLAB Coder software, in addition, your MATLAB code must not contain the “C++ Reserved Keywords” on page 19-67. C Reserved Keywords auto double int struct break else long switch case enum register typedef 19-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Paths and File Infrastructure Setup char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while C++ Reserved Keywords catch friend protected try class inline public typeid const_cast mutable reinterpret_cast typename delete namespace static_cast using dynamic_cast new template virtual explicit operator this wchar_t export private throw Reserved Keywords for Code Generation abs fortran localZCE rtNaN asm HAVESTDIO localZCSV SeedFileBuffer bool id_t matrix SeedFileBufferLen boolean_T int_T MODEL single byte_T int8_T MT TID01EQ char_T int16_T NCSTATES time_T cint8_T int32_T NULL true cint16_T int64_T NUMST TRUE cint32_T INTEGER_CODE pointer_T uint_T creal_T LINK_DATA_BUFFER_SIZE PROFILING_ENABLED creal32_T LINK_DATA_STREAM PROFILING_NUM_SAMPLES uint16_T creal64_T localB real_T uint32_T cuint8_T localC real32_T uint64_T uint8_T 19-67 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code cuint16_T localDWork real64_T UNUSED_PARAMETER cuint32_T localP RT USE_RTMODEL ERT localX RT_MALLOC VCAST_FLUSH_DATA false localXdis rtInf vector FALSE localXdot rtMinusInf MATLAB Coder Code Replacement Library Keywords The list of code replacement library (CRL) reserved keywords for your development environment varies depending on which CRLs currently are registered. Beyond the default ANSI, ISO, and GNU® CRLs provided with MATLAB Coder software, additional CRLs might be registered and available for use if you have installed other products that provide CRLs (for example, a target product), or if you have used Embedded Coder APIs to create and register custom CRLs. To generate a list of reserved keywords for the CRLs currently registered in your environment, use the following MATLAB function: crl_ids = RTW.TargetRegistry.getInstance.getTflReservedIdentifiers() This function returns an array of CRL keyword strings. Specifying the return argument is optional. Note: To list the CRLs currently registered in your environment, use the MATLAB command RTW.viewTfl. To generate a list of reserved keywords for the CRL that you are using to generate code, call the function passing the name of the CRL as displayed in the Code replacement library menu on the Code Generation > Interface pane of the Configuration Parameters dialog box. For example, crl_ids = RTW.TargetRegistry.getInstance.getTflReservedIdentifiers('GNU99 (GNU)') Here is a partial example of the function output: >> crl_ids = RTW.TargetRegistry.getInstance.getTflReservedIdentifiers('GNU99 (GNU)') crl_ids = 'exp10' 'exp10f' 19-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Paths and File Infrastructure Setup 'acosf' 'acoshf' 'asinf' 'asinhf' 'atanf' 'atanhf' ... 'rt_lu_cplx' 'rt_lu_cplx_sgl' 'rt_lu_real' 'rt_lu_real_sgl' 'rt_mod_boolean' 'rt_rem_boolean' 'strcpy' 'utAssert' Note: Some of the returned keyword strings appear with the suffix $N, for example, 'rt_atan2$N'. $N expands into the suffix _snf only if nonfinite numbers are supported. For example, 'rt_atan2$N' represents 'rt_atan2_snf' if nonfinite numbers are supported and 'rt_atan2' if nonfinite numbers are not supported. As a precaution, you should treat both forms of the keyword as reserved. Conventions for Naming Generated files The following table describes how MATLAB Coder names generated files. MATLAB Coder follows MATLAB conventions by providing platform-specific extensions for MEX files. Platform MEX File Extension MATLAB Coder Library MATLAB Coder Extension Executable Extension Linus Torvalds' Linux (32-bit) .mexglx .a None Linux x86-64 .mexa64 .a None Microsoft Windows (32-bit) .mexw32 .lib .exe Windows x64 .mexw64 .lib .exe 19-69 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code Generate Code for Multiple Entry-Point Functions In this section... “Advantages of Generating Code for More Than One Entry-Point Function” on page 19-70 “Generating Code for More Than One Entry-Point Function Using the Project Interface” on page 19-70 “Generating Code for More Than One Entry-Point Function at the Command Line” on page 19-72 “How to Call an Entry-Point Function in a MEX Function” on page 19-74 “How to Call an Entry-Point Function in a C/C++ Library Function from C/C++ Code” on page 19-74 Advantages of Generating Code for More Than One Entry-Point Function Generating a single C/C++ library for more than one entry-point MATLAB function allows you to: • Create C/C++ libraries containing multiple, compiled MATLAB files to integrate with larger C/C++ applications. • Share code efficiently between library functions. • Communicate between library functions using shared memory. Generating a MEX function for more than one entry-point function allows you to validate entry-point interactions in MATLAB before creating a C/C++ library. Generating Code for More Than One Entry-Point Function Using the Project Interface In the project, in the Entry-Point Files pane on the Overview tab, click the Add files link. Browse to the file that you want to add. Repeat this action for each entry-point file. By default, MATLAB Coder: • Lists the entry-point files alphabetically. • Generates a MEX function in the current folder. MATLAB Coder names the MEX function , fun_1_mex. fun_1 is the name of the first entry-point function. 19-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for Multiple Entry-Point Functions • Stores generated files in the subfolder codegen/mex/fun_1/. Generating a MEX Function with Two Entry-Point Functions Using the Project Interface Generate a MEX function with two entry-point functions, ep1 and ep2. Function ep1 takes one input, a single scalar, and ep2 takes two inputs, a double scalar and a double vector. 1 In a local writable folder, create a MATLAB file, ep1.m, that contains: function y = ep1(u) %#codegen y = u; 2 In the same folder, create a MATLAB file, ep2.m, that contains: function y = ep2(u, v) %#codegen y = u + v; 3 In the same folder, set up a MATLAB Coder project. a At the MATLAB command line, enter: coder -new ep.prj By default, the project opens in the MATLAB workspace on the right side. b On the project Overview tab, click the Add files link. Browse to the file ep1.m. Click OK to add the file to the project. c Define the type of input u. The file is displayed on the Overview tab, and the input is undefined. i d On the Overview tab, click the field to the right of the input parameter u and then, from the list of input options, select single. ii From the list of size options, select 1 x 1 to specify that u is a scalar. On the project Overview tab, click the Add files link. Browse to the file ep2.m. Click OK to add the file to the project. The file is displayed on the Overview tab, and the inputs are undefined. e Define the type of input u. i On the Overview tab, click the field to the right of the input parameter u and then, from the list of input options, select double. ii From the list of size options, select 1 x 1 to specify that u is a scalar. 19-71 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code f 4 Repeat the previous step for input v, setting the Size to 2x1. In the MATLAB Coder project, click the Build tab. By default, the Output type is MEX function and the Output file is ep1_mex. 5 On this tab, click the Build button to generate a MEX function using the default project settings. MATLAB Coder builds the project and, by default, generates a MEX function, ep1_mex, in the current folder. MATLAB Coder also generates other supporting files in a subfolder called codegen/mex/ep1_mex. MATLAB Coder uses the name of the MATLAB function as the root name for the generated files and creates a platformspecific extension for the MEX file, as described in “Naming Conventions” on page 19-66. You can now test your MEX function in MATLAB. For more information, see “How to Call an Entry-Point Function in a MEX Function” on page 19-74. Generating a C Static Library with Two Entry-Point Functions Using the Project Interface You can generate a C static library with two entry-point functions, ep1 and ep2, following the same project setup steps that you use to generate a MEX function. (See Generating a MEX Function with Two Entry-Point Functions Using the Project Interface.) When you build the project, set the Output type to C/C++ Static Library. MATLAB Coder builds the project and generates a C library, ep1, and supporting files in the default folder, codegen/lib/ep1. You can now test your library. For more information, see “How to Call an Entry-Point Function in a C/C++ Library Function from C/C++ Code” on page 19-74. Generating Code for More Than One Entry-Point Function at the Command Line To generate code for more than one entry-point function, use the following syntax, where global_options applies to functions, fun_1 through fun_n, and options_n applies only to the preceding function fun_n. codegen -global_options fun_1 -options_1 ... fun_n -options_n 19-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for Multiple Entry-Point Functions By default, codegen: • Generates a MEX function in the current folder. codegen names the MEX function, fun_mex. fun is the name of the alphabetically first entry-point function. Stores generated files in the subfolder codegen/mex/fun_1. fun_1 is the name of the first entry-point function. You can specify the output file name and subfolder name using the -o option. codegen -o out_fun In this case, codegen: fun_1 -options_1 ... fun_n -options_n • Generates a MEX function named out_fun_mex in the current folder. • Stores generated files in the subfolder codegen/mex/out_fun. For more information on setting build options at the command line, see codegen. Generating a MEX Function with Two Entry-Point Functions at the Command Line Generate a MEX function with two entry-point functions, ep1 and ep2. Function ep1 takes one input, a single scalar, and ep2 takes two inputs, a double scalar and a double vector. Using the -o option, name the generated MEX function sharedmex. codegen -o sharedmex ep1 -args single(0) ep2 -args { 0, zeros(1,1024) } codegen generates a MEX function named sharedmex.mex in the current folder and stores generated files in the subfolder codegen/mex/sharedmex. Generating a C/C++ Static Library with Two Entry-Point Functions at the Command Line Generate standalone C/C++ code and compile it to a library for two entry-point functions, ep1 and ep2. Function ep1 takes one input, a single scalar, and ep2 takes two inputs, a double scalar and a double vector. Use the -config:lib option to specify that the target is a library. Using the -o option, name the generated library sharedlib. codegen -config:lib -o sharedlib ep1 -args single(0) ep2 ... -args { 0, zeros(1,1024) } codegen generates C/C++ library code in the codegen/lib/sharedlib folder. For information on viewing entry-point functions in the code generation report, see “Code Generation Reports” on page 19-167. 19-73 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code How to Call an Entry-Point Function in a MEX Function To call an entry-point function in a MEX function that has more than one entry point, use this syntax: MEX_Function('entry_point_function_name', ... entry_point_function_param1, ... , entry_point_function_paramn) Calling an Entry-Point Function in a MEX Function Consider a MEX function, sharedmex, that has entry-point functions ep1 and ep2. Entry-point function ep1 takes one single scalar input and ep2 takes two inputs, a double scalar and a double vector. To call ep1 with an input parameter u, enter: sharedmex('ep1', u) To call ep2 with input parameters u and v, enter: sharedmex('ep2', u, v) How to Call an Entry-Point Function in a C/C++ Library Function from C/ C++ Code To call an entry-point function in a C/C++ library function from C/C++ code, write a main function in C/C++ that: • Includes the generated header files, which contain the function prototypes for the entry-point functions. • Calls the initialize function before calling the entry-point functions for the first time. • Calls the terminate function after calling the entry-point functions for the last time. • Configures your target to integrate this custom C/C++ main function with your generated code, as described in “Specify External File Locations” on page 22-12. • Generates the C/C++ executable using codegen. See the example, “Call a C Static Library Function from C Code” on page 22-2. 19-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for Global Data Generate Code for Global Data In this section... “Workflow” on page 19-75 “Declare Global Variables” on page 19-75 “Define Global Data” on page 19-76 “Synchronizing Global Data with MATLAB” on page 19-77 “Define Constant Global Data” on page 19-80 “Limitations of Using Global Data” on page 19-83 Workflow To generate C/C++ code from MATLAB code that uses global data: 1 Declare the variables as global in your code. 2 Before using the global data, define and initialize it. For more information, see “Define Global Data” on page 19-76. 3 Generate code from the MATLAB Coder project interface or using codegen. If you use global data, you must also specify whether you want to synchronize this data between MATLAB and the generated MEX function. For more information, see “Synchronizing Global Data with MATLAB” on page 19-77. Declare Global Variables When using global data, you must first declare the global variables in your MATLAB code. Consider the use_globals function that uses two global variables AR and B: function y = use_globals(u) %#codegen % Turn off inlining to make % generated code easier to read coder.inline('never'); % Declare AR and B as global variables global AR; global B; AR(1) = u + B(1); 19-75 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code y = AR * 2; Define Global Data You can define global data either in the MATLAB global workspace, in a MATLAB Coder project, or at the command line. If you do not initialize global data in a project or at the command line, MATLAB Coder looks for the variable in the MATLAB global workspace. If the variable does not exist, MATLAB Coder generates an error. Defining Global Data in the MATLAB Global Workspace To generate a MEX function for the use_globals function described in “Declare Global Variables” on page 19-75 using codegen: 1 In the MATLAB workspace, define and initialize the global data. At the MATLAB prompt, enter: global AR B; AR = ones(4); B=[1 2 3]; 2 Generate a MEX file. codegen use_globals -args {0} % Use the -args option to specify that the input u % is a real, scalar, double % By default, codegen generates a MEX function, % use_globals_mex, in the current folder Defining Global Data in a MATLAB Coder Project 1 On the project Overview tab, click Add global and enter a name for the global variable. By default, MATLAB Coder names the first global variable in a project g, and subsequent global variables g1, g2, etc. 2 After adding a global variable, before building the project, specify its type and initial value. For more information, see “Specifying Global Variable Type and Initial Value in a Project”. Note: If you do not specify the type, you must create a variable with the same name in the global workspace. 19-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for Global Data Defining Global Data at the Command Line To define global data at the command line, use the codegen -globals option. For example, to compile the use_globals function described in “Declare Global Variables” on page 19-75, specify two global inputs AR and B at the command line. Use the -args option to specify that the input u is a real, scalar double. By default, codegen generates a MEX function, use_globals_mex, in the current folder. codegen -globals {'AR',ones(4),'B',[1 2 3]} use_globals -args {0} Alternatively, specify the type and initial value with the -globals flag using the format -globals {'g', {type, initial_value}}. Defining Variable-Size Global Data To provide initial values for variable-size global data, specify the type and initial value with the -globals flag using the format -globals {'g', {type, initial_value}}. For example, to specify a global variable g1 that has an initial value [1 1] and upper bound [2 2], enter: codegen foo -globals {'g1', {coder.typeof(0, [2 2],1),[1 1]}} For a detailed explanation of the syntax, see coder.typeof. Synchronizing Global Data with MATLAB Why Synchronize Global Data? The generated MEX function and MATLAB each have their own copies of global data. To make these copies consistent, you must synchronize their global data whenever the two interact. If you do not synchronize the data, their global variables might differ. The level of interaction determines when to synchronize global data. For more information, see “When to Synchronize Global Data” on page 19-78. When global data is constant, you cannot synchronize the global data with MATLAB. By default, the MEX function tests for consistency between the compile-time constant global values and the MATLAB values at function entry and after extrinsic function calls. If the MATLAB values differ from the compile-time constant global values, the MEX function ends with an error. For information about controlling when the MEX function tests for consistency between the compile-time constant global values and the MATLAB values, see “Consistency Between MATLAB and Constant Global Data” on page 19-82. 19-77 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code When to Synchronize Global Data By default, synchronization between the MEX function's global data and MATLAB occurs at MEX function entry and exit and for extrinsic calls. Use this synchronization method for maximum consistency between the MEX function and MATLAB. To improve performance, you can: • Select to synchronize only at MEX function entry and exit points. • Disable synchronization when the global data does not interact. • Choose whether to synchronize before and after each extrinsic call. The following table summarizes which global data synchronization options to use. To learn how to set these options, see “How to Synchronize Global Data” on page 19-79. Global Data Synchronization Options If you want to... Set the global data synchronization mode to: Synchronize before and after extrinsic calls? Have maximum consistency when all extrinsic calls modify global data. At MEX-function entry, exit and extrinsic calls (default) Yes. Default behavior. Have maximum consistency At MEX-function when most extrinsic calls modify entry, exit and global data, but a few do not. extrinsic calls (default) Yes. Use the coder.extrinsic sync:off option to turn off synchronization for the extrinsic calls that do not change global data. Have maximum consistency At MEX-function when most extrinsic calls do not entry and exit modify global data, but a few do. Yes. Use the coder.extrinsic -sync:on option to synchronize only the calls that modify global data. Maximize performance when synchronizing global data, and none of your extrinsic calls modify global data. No. At MEX-function entry and exit 19-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for Global Data If you want to... Set the global data synchronization mode to: Synchronize before and after extrinsic calls? Communicate between generated MEX functions only. No interaction between MATLAB and MEX function global data. Disabled No. How to Synchronize Global Data To control global data synchronization, set the global data synchronization mode and select whether to synchronize extrinsic functions. For guidelines on which options to use, see “When to Synchronize Global Data” on page 19-78. You can control the global data synchronization mode from the project settings dialog box, the command line, or a MEX configuration dialog box. You control the synchronization of data with extrinsic functions using the coder.extrinsic -sync:on and -sync:off options. Controlling the Global Data Synchronization Mode in the Project Settings Dialog Box 1 On the MATLAB Coder project Build tab, verify that Output type is set to MEX Function and then click the More settings link. 2 On the Project Settings dialog box Memory tab, set Global data synchronization mode to At MEX-function entry and exit or Disabled, as applicable. Controlling the Global Data Synchronization Mode from the Command Line 1 In the MATLAB workspace, define the code generation configuration object. At the MATLAB command line, enter: mexcfg = coder.config('mex'); 2 At the MATLAB command line, set the GlobalDataSyncMethod property to SyncAtEntryAndExits or NoSync, as applicable. For example: mexcfg.GlobalDataSyncMethod = 'SyncAtEntryAndExits'; 3 When compiling your code, use the mexcfg configuration object. For example, to generate a MEX function for function foo that has no inputs: 19-79 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code codegen -config mexcfg foo Controlling Synchronization for Extrinsic Function Calls To control whether synchronization between MATLAB and MEX function global data occurs before and after you call an extrinsic function, use the coder.extrinsicsync:on and -sync:off options. By default, global data is: • Synchronized before and after each extrinsic call, if the global data synchronization mode is At MEX-function entry, exit and extrinsic calls. If you are sure that certain extrinsic calls do not change global data, turn off synchronization for these calls using the -sync:off option. For example, if functions foo1 and foo2 do not change global data, turn off synchronization for these functions: coder.extrinsic('-sync:off', 'foo1', 'foo2'); • Not synchronized, if the global data synchronization mode is At MEX-function entry and exit. If the code has a few extrinsic calls that change global data, turn on synchronization for these calls using the -sync:on option. For example, if functions foo1 and foo2 change global data, turn on synchronization for these functions: coder.extrinsic('-sync:on', 'foo1', 'foo2'); • Not synchronized, if the global data synchronization mode is Disabled. When synchronization is disabled, you cannot use the -sync:on option to control the synchronization for specific extrinsic calls. Define Constant Global Data If you know that the value of a global variable does not change at run time, you can reduce overhead in the generated code by specifying that the global variable has a constant value. You cannot write to the constant global variable. Define Constant Global Data Using the Project Interface 1 On the project Overview tab, click the field to the right of the global variable. 19-80 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Generate Code for Global Data 2 3 Select Define Constant Value. in the field to the right of the global variable, enter a MATLAB expression. Define Constant Global Data at the Command-Line Interface To specify that a global variable is constant using the codegen command, use the globals option with the coder.Constant class. 1 Define a configuration object for the code generation output type that you want. For example, define a configuration object for MEX code generation: 2 Use coder.Constant to specify that a global variable has a constant value. For example, the following code specifies that the global variable g has initial value 4 and that global variable gc has the constant value 42. cfg = coder.config('mex'); global_values = {'g', 4, 'gc', coder.Constant(42)}; 3 Generate the code using the -globals option. For example, generate code for myfunction specifying that the global variables are defined in the cell array global_values. 19-81 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪ ﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 19 Generating C/C++ Code from MATLAB Code codegen -config cfg -globals global_values myfunction Consistency Between MATLAB and Constant Global Data By default, the generated MEX function verifies that the values of constant global data in the MATLAB workspace are consistent with the compile-time values in the generated MEX. It tests for consistency at function entry and after calls to extrinsic functions. If the MEX function detects an inconsistency, it end