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

Viewed 542

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 Answers
Related