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
本地还是嵌套?
由于文档中提到的可变范围差异,因此可以快速测试
嵌套函数和本地函数之间的主要区别在于,嵌套函数可以使用父函数中定义的变量,而无需将这些变量显式地作为参数传递.
所以调整问题的例子:
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
语句.