How do I emulate 'include' behaviour in MATLAB?

matlab

Solution

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).

Problem

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.

Original source

Related problems