当不使用"end"时,一个.m文件中的多个函数是嵌套的还是本地的

Wol*_*fie 8 matlab function nested-function

在MATLAB中,您可以在一个.m文件中拥有多个功能.当然有main函数,然后是嵌套函数或本地函数.

每种功能类型的示例:

% 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
% ----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

使用函数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';
Run Code Online (Sandbox Code Playgroud)

有没有明确定义函数是写myotherfunc本地还是嵌套?

Wol*_*fie 8

由于文档中提到的可变范围差异,因此可以快速测试

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

所以调整问题的例子:

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;  
Run Code Online (Sandbox Code Playgroud)

这个错误因为myotherfunc实际上是一个本地函数,而不是一个嵌套函数.

嵌套函数文档支持该测试,该文档声明:

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