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

Are multiple functions in one .m file nested or local when "end" isn't used

在 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这样写的函数是局部的还是嵌套的,有明确的定义吗?

由于变量作用域的差异,这可以快速测试mentioned in the documentation

The primary difference between nested functions and local functions is that nested functions can use variables defined in parent functions without explicitly passing those variables as arguments.

所以改编问题示例:

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 支持该测试,其中指出:

Typically, functions do not require an end statement. However, to nest any function in a program file, all functions in that file must use an end statement.