MATLAB: Functions in different files

functionsnested functions

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…

Best Answer

I found a work-around!!
Might be useful to others.
I give the main script an input variable, say 'Fun'. And, say, if Fun=[] then the main() is run as it would be without this trick. Alternatively if main() is called with Fun='test' then main() bypasses its ordinary job and instead runs an "eval('strings = Fun(varargin)')" you know with the correct setting of this string.
So now I can run my external script even from within the main-file and the external script can call functions written inside the main-file.
Voila!
.m:
function Out = main(Fun,In,varargin)
if isempty(Fun)
%%%%
else
if ~isempty(varargin)
str = 'varargin{1}';
for n = 2:nargin-2
str = [str,',varargin{',num2str(n),'}'];
end
eval(sprintf('Out = %s(%s);',Fun,str))
else
eval(sprintf('Out = %s;',Fun))
end
end
end
function a = test(b)
a = b^2;
end
Related Question