Here is the problem: I have a .m file to test in which there is a main function and several internal functions called by the main one.
How can I call this internal function (to test them), from the console?
example:
function main
function_1;
function_1;
end
function_1
disp('this is');
end
function_2
disp(' an example');
end
How can I test it directly from the console?
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.
According to help function (see also the online doc):
Subfunctions are not visible outside the file where they are defined.
So you need a breakpoint, which will allow you to access the internal function as if you were doing it from within the .m file:
K>> prompt appears, you can call the internal function from the console.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With