How can I access subfunctions from outside the main function in MATLAB?
Show older comments
I have a function file that contains some subfunctions, as in the example below:
function foo1
disp('This function contains subfunctions it can call.')
foo2;
foo3;
function foo2
disp('in foo2');
function foo3
disp('in foo3');
I would like to access subfunctions "foo2" and "f003" from outside the function (similar to the "include" functionality in C).
Accepted Answer
More Answers (1)
Xiangrui Li
on 1 Aug 2020
Here are two methods I use to access local functions. The m file may look like this:
function varargout = myMainFunc(in, varargin)
% myMainFunc can do its own job as designed, and it typically calls those local
% functions within the m file.
% We mis-use the first two input, if any, to access all local functions
% You will need to insert this if-block into the beginning of your main function
if nargin>1 && (ischar(in) || isStringScalar(in))
if in == "LocalFunc" % call local function with optional input/output
[varargout{1:nargout}] = feval(varargin{:});
return; % we are accessing local function only, so skip rest in the main function
elseif in == "FuncHandle" % return a handle to use from outside the main function
varargout{1} = str2func(varargin{1});
return;
end
end
% Here may be the lengthy main code which calls local functions somewhere
out = mySubFunc(in); % the input can be any data type as designed
% ...
function out = mySubFunc(in1)
% This is the local function doing its own job
disp("Input to mySubFunc is " + in1);
out = in1 * 2;
Outside the m file, we can call mySubFunc directly:
myMainFunc('LocalFunc', 'mySubFunc', 123)
This gives
Input to mySubFunc is 123
If mySubFunc may be used multiple times, we can get its function handle to avoid above long syntax:
mySubFunc = myMainFunc('FuncHandle', 'mySubFunc'); % return the handle
mySubFunc(123) % use it like regular function
out = mySubFunc(3)
The varialbe input/output in the if-block will take care of possibly variable input/output of different local functions, so make the syntax more general. The only sacrifice is that the keywords LocalFunc and FuncHandle can not be used as general input to the main function.
Categories
Find more on Function Creation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!