MATLAB Answers

Calling sub-function (local function) from another file on Matlab

75 views (last 30 days)
Yonatan Nethanel
Yonatan Nethanel on 3 Sep 2019
Answered: Jan on 3 Sep 2019
I'm trying to figure out how to properly call a sub function from another .m file. I've searched for documentation, and only found the way of using function handles (as can be seen here:
The thing is that I think I've managed to find a way to it without using function handles, and want to know what am i doing and how does it works:
on main.m file:
function main
%function main...
function z = sub_function(x,y)
%function sub_function...
on outside.m file:
function call_to_local_function_from_outside
z = main('sub_function', x,y);
Appernalty, this is working, but why?


Show 3 older comments
Yonatan Nethanel
Yonatan Nethanel on 3 Sep 2019
@Adam my main function is a GUIDE app, and the outside function is also a GUIDE app called from the main GUIDE app
Adam on 3 Sep 2019
One would have to question why you would ever want to call a local function inside a GUI from outside, though. If the function is general enough to make sense to call from outside shouldn't it simply be in its own function file? If it is encapsulated within a GUIDE file (in so much as you could call that encapsulation!) then the whole point should be that it is hidden from the outside I would have thought.
Since there is apparently a Matlab page (in your link) dedicated to digging into files to make calls to local functions I guess there must be some valid use case for it, though I can't think of one.

Sign in to comment.

Answers (1)

Jan on 3 Sep 2019
This would work:
% main.m file: -----------
function out = main(Command, varargin)
switch Command
case 'sub_function'
out = sub_function(varargin{:});
function z = sub_function(x,y)
z = x + y;
% outside.m file: -----------
function outside
x = rand
y = rand
z = main('sub_function', x, y);
Although this is working, it is an unnecessary indirection. This increases the level of complexity, because it forwards the local function to global calls. This means drilling a hole into the concept of local or private subfunction. It is leaner and cleaner to move sub_function() to an externally visible function in an own file, when you want to call it from the outside.
A real need to hide a subfunction can be a function name, which is used mutliple times. Then a "package" is usefull: the "+" in the folder name.


Sign in to comment.