Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call internal function of a .m from the command prompt?

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?

like image 719
Bobo87 Avatar asked Oct 03 '22 16:10

Bobo87


2 Answers

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.

like image 155
chappjc Avatar answered Oct 13 '22 10:10

chappjc


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:

  1. Set a breakpoint at some point within the main function of the .m file
  2. Run the .m file
  3. When the K>> prompt appears, you can call the internal function from the console.
like image 44
Luis Mendo Avatar answered Oct 13 '22 11:10

Luis Mendo