You actually can use an internal (local) function outside of the M file in which it is defined, if you have it's handle. For example, the following function returns the handles to all the subfunctions with the localfunctions
command,
% internalHandlesTest.m
function [out,hl] = internalHandlesTest(in)
out = subfun1(in);
% hl = @subfun1; % just to get one internal function handle
hl = localfunctions; % to get all internal function handles
end
function subout = subfun1(subin)
% still internalHandlesTest.m
fprintf('You are using internalHandlesTest>subfun1!\n');
subout = subin;
end
function subfun2()
% still internalHandlesTest.m
fprintf('You are using internalHandlesTest>subfun2!\n');
end
Let's try it:
>> [out,hl] = internalHandlesTest(0);
You are using internalHandlesTest>subfun1!
>> disp(hl)
@subfun1
@subfun2
>> hl{1}(1)
You are using internalHandlesTest>subfun1!
ans =
1
>> hl{2}()
You are using internalHandlesTest>subfun2!
>>
So, we can use internal functions outside of the M file. These functions are of type scopedfunctions
, and we are able to do this because MATLAB keeps track of it's parentage
and the source file. See the output of the functions
command on these handles:
>> functions(hl{1})
ans =
function: 'subfun1'
type: 'scopedfunction'
file: 'E:\Users\jchappelow\Documents\MATLAB\internalHandlesTest.m'
parentage: {'subfun1' 'internalHandlesTest'}
Of course, you can see the help for internal functions quite easily:
>> help internalHandlesTest>subfun1
still internalHandlesTest.m
But to run local functions, you need to get a function handle, which can only be obtained via an output argument of the canonical function.