What is the closest thing MATLAB has to namespaces?

后端 未结 4 1930
挽巷
挽巷 2020-11-28 23:55

We have a lot of MATLAB code in my lab. The problem is there\'s really no way to organize it. Since all the functions have to be in the same folder to be called (or you have

4条回答
  •  盖世英雄少女心
    2020-11-29 00:12

    The package system is probably the best. I use the class system (@ClassName folder), but I actually write objects. If you're not doing that, it's silly just to write a bunch of static methods. One thing that can be helpful is to put all your matlab code into a folder that isn't on the matlab path. Then you can selectively add just the code you need to the path.

    So say you have two projects, stored in "c:\matlabcode\foo" and "c"\matlabcode\bar", that both use common code stored in "c:\matlabcode\common," you might have a function "setupPaths.m" like this:

    function setupPaths(projectName)
    basedir = fullfile('c:', 'matlabcode');
    addpath(genpath(fullfile(basedir, projectName)));
    switch (projectName)
       case {'foo', 'bar'}
           addpath(genpath(fullfile(basedir, 'common')));
    end
    

    Of course you could extend this. An obvious extension would be to include a text file in each directory saying what other directories should be added to the path to use the functions in that directory.

    Another useful thing if you share code is to set up a "user specific/LabMember" directory structure, where you have different lab members save code they are working on. That way you have access to their code if you need it, but don't get clobbered when they write a function with the same name as one of yours.

提交回复
热议问题