Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I emulate 'include' behaviour in MATLAB?

Tags:

matlab

In MATLAB I can define multiple functions in one file, with only the first defined function being visible external to that file. Alternatively, I can put each function in its own file and make them all globally visible through the path. I'm writing a menu driven application, where each menu item runs a different function. Currently, these are all in one big file, which is getting increasingly difficult to navigate. What I'd like to do is put groups of related functions into separate files.

I think I can do something like this by putting all the child functions into a separate directory and then adding the directory to the path in my parent function, but this feels a bit messy and inelegant.

Can anyone make a better suggestion?

Note: I'm most familiar with MATLAB 2006, but I'm in the process of upgrading to MATLAB 2009.

like image 275
Ian Hopkinson Avatar asked Aug 14 '09 12:08

Ian Hopkinson


3 Answers

One suggestion, which would avoid having to modify the MATLAB path, is to use a private function directory. For example:

Let's say you have a function called test.m in the directory \MATLAB\temp\ (which is already on the MATLAB path). If there are local functions in test.m that you want to place in their own m-files, and you only want test.m to have access to them, you would first create a subdirectory in \MATLAB\temp\ called private. Then, put the individual local function m-files from test.m in this private subdirectory.

The private subdirectory doesn't need to be added to the MATLAB path (in fact, it shouldn't be added to the path for things to work properly). Only the file test.m and other m-files in the directory immediately above the private subdirectory have access to the functions it contains. Using private functions, you can effectively emulate the behavior of local functions (i.e. limited scope, function overloading, etc.) without having to put all the functions in the same m-file (which can get very big for some applications).

like image 127
gnovice Avatar answered Nov 20 '22 08:11

gnovice


Maybe something like this,

function foobar
    addpath C:\Include\ModuleX

    %% Script file residing in ModuleX
    some_func();
end

Of course, ModuleX will remain in your search path after exiting foobar. If you want to set it to the default path without restarting, then add this line:

path(pathdef)

See ADDPATH for more details.

like image 25
Jacob Avatar answered Nov 20 '22 08:11

Jacob


You can use sub-folders that begin with "+" to separate functions into namespaces.

For example:

Place a function "bar" in the folder "+foo"

function bar()
print('hello world');

This function can be used as:

foo.bar() % prints hello world

More information can be found here:

What is the closest thing MATLAB has to namespaces?

like image 1
user2599450 Avatar answered Nov 20 '22 07:11

user2599450