How do I emulate 'include' behaviour in 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.


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 MATLABtemp (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 MATLABtemp 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 (ie 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).


Maybe something like this,

function foobar
    addpath C:IncludeModuleX

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


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?

链接地址: http://www.djcxy.com/p/84182.html

上一篇: MatLab ODE启动/停止条件

下一篇: 如何在MATLAB中模拟'包含'行为?