What is the MATLABPATH variable and how do I change it?
The MATLABPATH variable is set in the Matlab script to include all the Matlab Toolbox directories and some local contrib directories. Also included is the directory ~/matlab if it exists.
Matlab uses the following steps to determine what to do with a name you specify (on the command line or in a function):
- checks to see if 'name' is a variable
- checks for 'name' as a built-in function
- checks to see if 'name' is a file in the current directory (name.m or name.mat for load command)
- searches the directories specified by the environment variable MATLABPATH.
There are 3 ways to modify the MATLABPATH:
Command line
For adding directories to the MATLABPATH ( the list of directories Matlab searchs for .m and .mat files) at run time, you can do:
add matlab matlab /dir1 /dir2 /dir3
The Matlab startup script will append /dir1 /dir2 and /dir3 to MATLABPATH if the directories exist. A key feature to this method is that the directories added appear after the default MATLABPATH.
Environment variable
If the environment variable MATLABPATH is set when you start Matlab, the directories in MATLABPATH are prepended to the default MATLABPATH. Since the current working directory is always searched before MATLABPATH, it is not necessary to include '.' in the MATLABPATH variable. A key feature to this method is that added directories appear before the Matlab toolboxes. Also, there is no error checking at start up to see if the directories exist.
Inside Matlab
Once you have started Matlab or on startup, if you need more options than provided above, you can use the Matlab "addpath" or "path" commands.
The "addpath" command allows you to choose between prepending (default) or appending directories to the path.
>> addpath /dir1 /dir2 /dir3 % prepends directories to path >> addpath /dir1 /dir2 /dir3 -end % appends directories to path
The "path" command can be used to modify the path using strings. For example:
>> p = path; % this gets current path >> path(p,'/usr/users/work') % this appends the directory % /usr/users/work to MATLABPATH >> path('/usr/users/thesis',p) % this prepends the directory % /usr/users/thesis to MATLABPATH
If you want a specialized path every time you start Matlab, here is what you would do:
- If you do not have a ~/matlab directory, create one.
- In that directory, create a file startup.m, that contains the desired "addpath" or "path" commands. Matlab checks for this file each time it starts up. If it exists, it is executed automatically.
With this method you are not restricted to either appending or prepending to MATLABPATH. You can use the full programming facilities of Matlab to build a custom search path.