functions in different files
Show older comments
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...
Accepted Answer
More Answers (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
on 2 Sep 2016
1 vote
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.
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!