MATLAB支持前向声明吗? [英] Are forward declarations supported in MATLAB?
问题描述
是否可以在m文件中使用一个函数,该文件在同一文件的后面部分中实现:与其他编程语言(如C?)具有相似的风格?
函数y = main_func(x)
%#这是主函数
y = helper_func1(x)。* helper_func2(x); %#只是一个例子
函数h1 = helper_func1(x)
%#这是一个辅助函数#1
h1 = x + 2; %#只是一个例子
函数h2 = helper_func2(x)
%#这是一个辅助函数#2
h2 = x * 2; %#只是一个例子
在这个例子中 main_func
可以在没有任何问题的情况下调用 helper_func1
和 helper_func2
。您可以测试运行它并亲自查看:
>> main_func(8)
ans =
160
不需要任何前向声明。
顺便说一下,MATLAB中的很多m文件都是以这种方式实现的。例如, corrcoef
一>。使用键入corrcoef
,您可以看到。
注意:本地函数定义不允许出现在提示符处或脚本,所以你必须在你的m文件中声明一个main函数。作为一个练习,将我的示例复制粘贴到一个新的m文件中,删除 main_func
的声明(仅第一行),看看会发生什么。
Is it possible to use a function in a m-file, which is implemented in a later part of the same file: in similar style to other programming languages such as C?
Of course.
In such an m-file, the local functions would be declared after the main function. For example:
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
In this example main_func
can invoke helper_func1
and helper_func2
without any problems. You can test-run it and see for yourself:
>> main_func(8)
ans =
160
There is no need for any forward declaration.
By the way, a lot of m-files that come with MATLAB are implemented this way. For instance, corrcoef
. With type corrcoef
, you can see that.
Note: local function definitions are not permitted at the prompt or in scripts, so you have to have declare a "main" function in your m-file. As an exercise, copy-paste my example into a new m-file, remove the declaration of main_func
(only the first line) and see what happens.
这篇关于MATLAB支持前向声明吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!