tags:

views:

328

answers:

2

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.

+1  A: 

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.

Jacob
+1 because this is a reasonable solution which I'd considered.
Ian Hopkinson
+6  A: 

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 subfunctions 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 subfunction 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 subfunctions (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).

gnovice
I didn't know you could do this. I'll give it a go to see how it works out. At least all the function files will be hidden in a quiet corner!
Ian Hopkinson

related questions