functions in different files
显示 更早的评论
Here is one...
I have a main()-function in main.m, and the file includes a subfunction()-function, like:
function main
b = subfunction(c);
f = external(c);
function b = subfunction(c)
b = c^2;
end
and I have an external()-function in external.m, like
function d = external(e)
d = subfunction(e)*2;
I would like to keep the external()-function in this separate file, but I would like it to be able to use sub-functions in the main file. Now I would have expected, since the main.m is initiated that all subfunctions within it was then "declared" globally, but it turns out that the external function can't call the subfunction, even if it has been called before the external function calls it.
Is there a work-around?
Why? I share the main() with other users, and develop the external() until some point of sharing. Until then I would like to keep it private, but still being able to exploit subfunctions. Alternatively I would need to copy all subfunctions in main() that I need into the external.m or into separate files... But when I share stuff, it is sometimes nice not to send hundreds of files around...
采纳的回答
更多回答(2 个)
Sub-functions have file scope. If you want functions to be seen publicly they either need to be each in their own file or they need to be public methods on a class.
Calling the main function of a file has no bearing on external functions suddenly being able to access the local functions of that file - they are effectively like private functions of a class that don't suddenly get exposed when you start using the class.
You can make use of package folders to group functions, but they still need to be in their own file. You can also zip up folders to send them, of course, rather than sending a load of .m files as they are.
Steven Lord
2016-9-2
1 个投票
Consider making the subfunction a private function instead of a subfunction. This will prevent arbitrary functions from calling it while still making it accessible to the functions in the directory containing the private subdirectory.
类别
在 帮助中心 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!