Skip to content

Instantly share code, notes, and snippets.

@biogeo
Created September 18, 2013 20:43
Show Gist options
  • Save biogeo/6615380 to your computer and use it in GitHub Desktop.
Save biogeo/6615380 to your computer and use it in GitHub Desktop.
When using Matlab in a shared work environment, sometimes it's possible for name conflicts to occur, in which two people have different scripts of the same name. Alice and Bob might both have scripts called "myScript.m", for example, and if Bob's script is higher on the path, then when Alice calls "myScript", she will get Bob's version instead o…
function add_my_paths
% This function should be given a specific name for each user.
% It is the one file that needs to be named appropriately in order to guarantee name collision avoidance.
% This needs to be a function instead of a script because we will need a subfunction to recursively add subdirectories.
% For this example, we will add the directory that contains the script, as well as all of its subdirectories, to the Matlab path.
% mfilename('fullfile') returns the full path to the currently running script, as in '/home/user/matlab/Alice/add_my_paths.m'
thisPath = mfilename('fullfile');
% Get path to the directory containing the currently running script.
thisDir = fileparts(thisPath);
% Alternatively, thisDir could just be specified as a string literal, as in:
% thisDir = '/home/user/matlab/Alice';
% In this case, thisPath does not need to be assigned.
% Use a recursive function call to actually add the desired directory with all its subdirectories:
add_with_subdirs(thisDir);
% Note that you could instead just call:
% addpath(genpath(thisDir));
% and be done. However, genpath obnoxiously includes hidden directories (those beginning with a '.'), which
% can be a problem if, for example, you are transferring files between Mac and Windows, and generating lots
% of '._DSStore' directories, or using version control like Git or Mercurial. The add_with_subdirs function
% excludes directories beginning with '.' as well.
function add_with_subdirs(p)
% Add the current directory
addpath(p);
% Retrieve directory contents and iterate over all of them
s = dir(p);
for i=1:numel(s)
% For each subdirectory...
if s(i).isdir
% Check if this is a valid subdirectory to add to the path.
% Valid subdirectories will not begin with the characters '.' (hidden directory),
% '@' (a Matlab class directory), or '+' (a Matlab package directory), or be named
% 'private'.
if ~ismember(s(i).name(1), '.@+') && ~strcmp(s(i).name, 'private')
% If the subdirectory name is valid, add it to the path as well
add_with_subdirs(fullfile(p,s(i).name));
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment