How can I write all functions in one source file and still be able to access them in MATLAB 7.8 (R2009a)

2 views (last 30 days)
I am currently attempting to write MATLAB functions which will serve as utilities to many of the other MATLAB scripts and functions that I will be writing. As many of these functions contain only a few lines of code, I would like to be able to place all the functions in one single source file instead of creating a separate file for each of the functions.
When I do this, all functions in the file except for the one that has the same name as the MATLAB file seem to be accessible only within this source file.
Is there any way I can make these functions accessible outside this source file?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 21 Jan 2010
The subfunctions present in a MATLAB file can be made accessible to other functions and scripts, if a handle is passed to these subfunctions. However, this handle has to be created within the scope of this MATLAB file. The code below describes how you can write a function called "obtain_fn_handle" which would allow you to do this.
function fn_handle = obtain_fn_handle(fn_name)
% This function returns function handles of one of the three subfunctions to
% the calling function based upon the function name being passed as
% input. The valid values for input are 'dispstring', 'increment' and
% 'decrement'
switch( lower(fn_name) )
case 'dispstring'
fn_handle = @dispstring;
case 'increment'
fn_handle = @increment;
case 'decrement'
fn_handle = @decrement;
otherwise
fn_handle = -1;
end
end
function dispstring(ip_string)
disp(ip_string)
end
function ip_val = increment(ip_val)
ip_val = ip_val+1;
end
function ip_val = decrement(ip_val)
ip_val = ip_val-1;
end
This code allows you to obtain handles to the subfunctions in the file thereby allowing you to use the functionality. You can make use of the function "increment" in this MATLAB file using the code below:
fn = obtain_fn_handle('increment');
a = 10;
b = fn(a);

More Answers (0)

Categories

Find more on Programming Utilities in Help Center and File Exchange

Products


Release

R2009a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!