Management of your search path in Matlab is an important skill that every Matlab programmer should have. Your search path is the ordered set of directories that Matlab uses to find a function that you call. Being aware of your search path is a good habit, especially if you are working with multiple versions of the same code. In this post and the following post, I will describe how to use Matlab to modify your search path.
The first command with which you should familiarize yourself is path. Path can be used to view or change your search path in the command window. If you type path at the command line, you will see a list of directories similar to this:
Your default search path will consist of a list of the directories that contain the Matlab toolboxes installed on your computer and end with your ‘work’ directory. The directories in your default search path will always begin with matlabroot, which is the root folder where Matlab is installed on your computer. On my computer, matlabroot is ‘C:\MATLAB7’. You can type matlabroot into the command line to check your own root directory.
Let’s do an example to show how to add and remove directories to and from your search path. Assume that your search path looks like the one above and that you want to add directories to your path that contain some scripts that you want to use.
This command will add ‘directory’ to the beginning of your search path. Your search path will then look like this:
Assume that you have two subdirectories within your directory named ‘subdir1’ and ‘subdir2’ and that ‘subdir1’ has a subdirectory named ‘subdir11’. Matlab has a useful function called genpath that generates a path string of all the subdirectories within a directory.
Your path will now look like this:
After you add your directories to the search path, you will be able to run your scripts in those directories while working in any other directory. This is a nice feature, since you don’t have to worry about changing directories whenever you want to run different scripts. When you no longer want to use scripts from the directories in your new search path, you can easily remove them by using the command rmpath.
Your search path will now look like the original search path. The default search path is saved in an autogenerated file called pathdef.m, and when Matlab starts up, the search path is created based on this file. That means that you do not have to change the Matlab search path back to the way it was before you modified the search path. In the next post, I will write more about modifying the search path for future sessions, as well as some other issues regarding the search path.