当一个.m文件中的多个函数嵌套或本地时," end"没用过

时间:2017-09-13 14:26:11

标签: matlab function nested-function

在MATLAB中,您可以在一个.m文件中拥有多个功能。当然有主要功能,然后是nested or local functions

每种功能类型的示例:

% myfunc.m with local function ------------------------------------------
function myfunc()
    disp(mylocalfunc());
end
function output = mylocalfunc()
    % local function, no visibility of variables local to myfunc()
    output = 'hello world';
end
% -----------------------------------------------------------------------

% myfunc.m with nested function -----------------------------------------
function myfunc()
    disp(mynestedfunc());
    function output = mynestedfunc()
        % nested function, has visibility of variables local to myfunc()
        output = 'hello world';
    end
end
% ----------------------------------------------------------------------

使用这些功能时,差异很明显。 end陈述。但是,我不认为你没有清楚地记录了你正在使用的内容,因为这是有效的语法:

% myfunc.m with some other function 
function myfunc()
    disp(myotherfunc());
function output = myotherfunc()
    % It's not immediately clear whether this is nested or local!
    output = 'hello world';

是否有明确定义myotherfunc这样的函数是本地函数还是嵌套函数?

1 个答案:

答案 0 :(得分:8)

由于范围差异mentioned in the documentation

,因此可以快速测试
  

嵌套函数和局部函数之间的主要区别在于嵌套函数可以使用在父函数中定义的变量,而不会将这些变量显式地作为参数传递。

所以调整问题的例子:

function myfunc()
    % Define some variable 'str' inside the scope of myfunc()
    str = 'hello world';
    disp(myotherfunc());
function output = myotherfunc()
    % This gives an error because myotherfunc() has no visibility of 'str'!
    output = str;  

此错误,因为 myotherfunc实际上是本地函数,而不是嵌套函数。

documentation for nested functions支持该测试,其中指出:

  

通常,函数不需要end语句。但是,要在程序文件中嵌套任何函数,该文件中的所有函数必须使用end 语句。