Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling local functions from command line

I have a local function defined in an m-file. For example:

% begining of public_function.m file
function fh = public_function( )
%
% do some computation...

fh = @local_function; % return function handle to local function defined below

function y = local_function( x )
% 
% a local function inside public_function.m file
% 

% some manipulation on x
y = x;

% end of public_function.m file NOTE THAT local_function is NOT nested

Now, I would like to call local_function from command line (and not from public_function). I was able to do so using the function handle returned from public_function:

>> fh = public_function(); % got handle to local_function
>> y = fh( x ); % calling the local function from command line :-)

My question:
Is there any other way (apart from explicitly pass the function handle) to call local function from command line (or other m-file/functions)?

More precisely, I want a method to access any local function in a file (provided that I know its name). So, if I have public_function.m file (and function) and I know that local_function is local to that file, is there a way to access local_function from command line ?

like image 307
Shai Avatar asked Mar 17 '13 13:03

Shai


People also ask

Can you create a local function using the Command Window?

Restrictions for Local Functions and Variables Local functions are only visible within the file where they are defined. They are not visible to functions in other files, and cannot be called from the Command Window.

How do you call a function in the Command Window in MATLAB?

Go to the Editor tab and click Run . MATLAB® displays the list of commands available for running the function. Click the last item in the list and replace the text type code to run with a call to the function including the required input arguments.

How do local functions work in MATLAB?

Local functions are subroutines that are available within the same file. Local functions are the most common way to break up programmatic tasks. In a function file, which contains only function definitions, local functions can appear in the file in any order after the main function in the file.


1 Answers

The official documentation says that:

... you cannot call a local function from the command line or from functions in other files.

According to this, you must pass its handle to the caller in order to allow invoking it indirectly outside its m-file. I believe that there is no documented sensible way to access local functions otherwise.

Oddly though, you can still do this with help:

help public_function>local_function
like image 153
Eitan T Avatar answered Oct 29 '22 08:10

Eitan T