Pet*_*tig 11 matlab function forward-declaration
是否可以在m文件中使用函数,该文件在同一文件的后续部分中实现:与其他编程语言(如C)类似?
Eit*_*n T 14
当然.
在这样的m文件中,本地函数将在main函数之后声明.例如:
function y = main_func(x)
% # This is the main function
y = helper_func1(x) .* helper_func2(x); % # Just an example
function h1 = helper_func1(x)
% # This is a helper function #1
h1 = x + 2; % # Just an example
function h2 = helper_func2(x)
% # This is a helper function #2
h2 = x * 2; % # Just an example
Run Code Online (Sandbox Code Playgroud)
在这个例子中main_func可以调用helper_func1并且helper_func2没有任何问题.您可以测试运行它并亲眼看看:
>> main_func(8)
ans =
160
Run Code Online (Sandbox Code Playgroud)
没有必要进行任何前瞻性声明.
顺便说一下,MATLAB附带的很多m文件都是以这种方式实现的.例如,corrcoef.有了type corrcoef,你可以看到.
注意:在提示符或脚本中不允许使用本地函数定义,因此必须在m文件中声明"main"函数.作为练习,将我的示例复制粘贴到一个新的m文件中,删除main_func(仅第一行)的声明,看看会发生什么.