Is there any way to call a MATLAB "subfunction" from the outside the file? [duplicate]
Possible Duplicate:
Is it possible to define more than one function per file in MATLAB?
In order to define a (not anonymous) function in MATLAB, you need to create a file with the same name as the function; e.g., a function called myfunc can be defined in a file myfunc.m as per:
function rtn = myfunc(arg)
% do some stuff
end
Suppose in this same file myfunc.m, I have also a sub-function, as in
function rtn = myfunc(arg)
% do some stuff
end
function rtn = mysubfunc(arg)
% do some other stuff
end
AFAIK, there is no way to access mysubfunc from execu开发者_开发技巧tion happening anywhere outside of the subfunc.m file. I have been and continue to be annoyed by this little idiosyncrasy in MATLAB (R2010b). Am I wrong -- is there any way to call mysubfunc from outside myfunc.m?
Update: New question: Is there any good way to do this? or should I really just suck it up and keep on making more files?
You could make them all static methods on a utility class. The functions will be globally referenceable by name, but you only need to manage one M-file.
classdef mystuff % in mystuff.m
%MYSTUFF Utility functions for something or other...
methods (Static = true)
function rtn = myfunc(arg)
disp('myfunc');
end
function rtn = mysubfunc(arg)
disp('mysubfunc');
end
end
end
On the downside, you'll need to qualify or import all references to them, like mystuff.myfunc(). An "import mystuff.*" can take care of this for code outside of the class.
import mystuff.*
myfunc()
mysubfunc()
Within the class, calls between the functions will need to be qualified. (Big wart in Matlab's MCOS syntax, IMHO.) Also, they'll have more calling overhead than regular functions, so your code will be slower if you're calling them in tight loops. On the upside, now they're class members, and you can refactor them to make use of private class fields and functions and so on.
If you want to organize your codebase, you can stick them in a namespace by putting them in a directory whose name starts with a "+". Same number of files, but at least you have some structure to your dirs.
Accessing through function handles. It can be seen as OO emulation (static methods). I do not recommend you to use this technique though.
function obj = mainFunc()
obj.myFunc = @myFunc;
obj.mySubFunc = @mySubFunc;
end
function rtn = myFunc(arg)
% do some stuff
end
function rtn = mySubFunc(arg)
% do some other stuff
end
精彩评论