函数定义
在创建用于 MATLAB Function 模块的 MATLAB® 函数时,有一些特殊的注意事项。例如,使用 varargin
和 varargout
、递归函数、匿名函数和嵌套函数时,存在某些限制。为了生成 MATLAB 递归函数的代码,代码生成器使用编译时递归或运行时递归。为了生成高效的 C/C++ 代码,代码生成器有时会创建一个函数的多个版本,称为函数特化。在某些情况下,您可以通过使用 coder.ignoreSize
和 coder.ignoreConst
来阻止代码生成器创建函数特化。您可以绕过 MATLAB 代码中特定函数的代码生成,改用 MATLAB 引擎来执行调用。为此,请使用 coder.extrinsic
构造。
模块
MATLAB Function | 在 Simulink 模型中包含 MATLAB 代码 |
MATLAB System | 在模型中包含 System object |
函数
coder.extrinsic | 将函数声明为外部函数,并在 MATLAB 中执行它 |
coder.ignoreSize | Prevent code generator from creating function specializations for constant-size expressions |
coder.ignoreConst | 防止将表达式的常量值用于函数特化 |
coder.mustBeConst | 验证值为编译时常量 (自 R2023b 起) |
coder.unroll | 通过为每次循环迭代生成循环体的副本来展开 for 循环 |
coder.sameSizeBinaryOp | Apply element-wise binary operations without implicit expansion (自 R2021b 起) |
coder.noImplicitExpansionInFunction | Disable implicit expansion within the specified function in the generated code (自 R2021b 起) |
coder.read | 运行时在生成的代码中读取数据文件 (自 R2023a 起) |
coder.write | 创建生成的代码在运行时读取的数据文件 (自 R2023a 起) |
主题
- 编译指令 %#codegen
指示 MATLAB 函数用于代码生成。
- 生成启用隐式扩展的代码
代码生成器在生成的代码中引入修改以实现隐式扩展。
- 优化生成代码中的隐式扩展
默认情况下,生成代码中的隐式扩展是启用的。代码生成器在生成的代码中引入修改以执行隐式扩展。生成的代码中的更改可能导致额外的代码来扩展操作数。操作数的扩展可能会影响生成代码的性能。请参阅生成启用隐式扩展的代码 (MATLAB Coder)。
- Code Generation for Variable Length Argument Lists
Generate code for
varargin
andvarargout
. - 为用于验证输入和输出参量的 arguments 代码块生成代码
为用于约束函数输入和输出值的类、大小和其他方面 MATLAB 代码生成代码。
- 递归函数的代码生成
在用于代码生成的 MATLAB 代码中使用递归函数。
- Force Code Generator to Use Run-Time Recursion
Rewrite your MATLAB code so that the code generator uses run-time recursion instead of compile-time recursion.
- 匿名函数的代码生成
在用于代码生成的 MATLAB 代码中使用匿名函数。
- Code Generation for Nested Functions
Use nested functions in MATLAB code intended for code generation.
- 代码生成的函数调用解析
代码生成器使用优先级规则来解析函数调用。
- 代码生成路径中文件类型的解析
代码生成器使用优先级规则来解析文件类型。
- 使用 MATLAB 引擎在 MATLAB Function 模块中执行函数调用
如果代码生成不支持某个函数,请将其声明为外部函数以在 MATLAB 中执行。
疑难解答
for 循环中 varargin 或 varargout 的非常量索引
当代码生成器无法确定 varargin
或 varargout
中的索引值时,强制循环展开。
Avoid Duplicate Functions in Generated Code
Reduce the occurrence of duplicate functions in the generated code.
Output Variable Must Be Assigned Before Run-Time Recursive Call
Troubleshoot output variable assignment for run-time recursion.
Compile-Time Recursion Limit Reached
Troubleshoot compile-time recursion limit error.
对代码生成过程中出现的大小不兼容性错误进行故障排除。