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

一笑奈何 提交于 2019-12-08 17:06:23

问题


In MATLAB you can have multiple functions in one .m file. There is of course the main function, and then either nested or local functions.

Examples of each function type:

% 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
% ----------------------------------------------------------------------

The difference is clear when you use the functions' end statements. However, I don't think it's clearly documented which you are using when you don't, since this is valid syntax:

% 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';

Is there any clear definition of whether functions written like myotherfunc are local or nested?


回答1:


This can be quickly tested because of the variable scope differences 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.

So adapting the question example:

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;  

This errors because myotherfunc is in fact a local function, not a nested function.

The test is supported by the documentation for nested functions which states:

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.



来源:https://stackoverflow.com/questions/46200119/are-multiple-functions-in-one-m-file-nested-or-local-when-end-isnt-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!