MATLAB - Avoiding the CD command
18 Mar 2009 Quan Quach 9 comments 1,319 views
The CD command allows you to change the working directory. Most people use this command to either move to a particular directory wherein input files are stored or to move to a directory to write output files. In theory, there isn’t anything wrong with changing the working directory in the middle of a script/function. But in practice, it’s better to avoid doing that. In this post, we’ll discuss using the FULLFILE command to help us avoid the CD command.
Contents
- The CD Command - Good or Evil?
- Example of Script using CD
- FULLFILE is your Friend: Example of Script without CD
- Absolute is Better than Relative!
The CD Command - Good or Evil?
To me, the CD command shouldn’t be used if it can be avoided. When commands such as IMPORTDATA, XLSREAD, XLSWRITE, LOAD, SAVEAS, etc are used, they require an input string that designates the file name. If the files are stored within the MATLAB current directory from where the m-file is being executed, then you don’t have to include the entire path name of the file. For example, you can do the following:
%this command will work if the file is located in the current directory load('mydata.txt')
But if you specified the full file path, as shown in the example below, then it doesn’t matter where the file is located!
%this command will work no matter what directory the m-file is running from load('C:/MATLAB/blinkdagger/data/mydata.txt.')
Example of Script using CD
A lot of times, people will use the CD command to move to a designated directory in order to write output files. Here’s an example of a script that does this.
currentDir = pwd; %save the current directory %outputDir is the directory where we'll write the output outputDir = 'C:/output'; %outputFileName is the name of the output file outputFileName = 'myData.xls'; cd(outputDir) %change directory xlswrite(outputFileName ,data) %write the output data in Excel cd(currentDir) % go back to the original directory
FULLFILE is your Friend: Example of Script without CD
Instead of doing the above, there’s an easier, and less cumbersome way that will make your code more robust. By using absolute file paths, we can avoid using the CD command. Notice that we don’t have to change the directory, write the output file, and then change back to the original directory.
%outputDir is the directory where we'll write the output outputDir = 'C:/output'; %outputFileName is the name of the output file outputFileName = 'myData.xls'; %build the full path of the outputfile fullPath = fullfille(outputDir,outputFileName); xlswrite(fullPath ,data) %write the output data in Excel
Another reason why I like the FULLFILE command is because I don’t have to worry that I have the appropriate number of ‘”/” in my file path. FULLFILE makes sure that the path name is arranged correctly.
Absolute is better than Relative!
The lesson learned in this post is that absolute file paths are more robust than relative file paths. In general, it’s good practice to use the absolute file path instead of the relative ones as it will make your code more flexible and portable.
9 Responses to “MATLAB - Avoiding the CD command”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


There are other benefit to not using CD when writing to a file than just potential confusion about where the file has been written.
Suppose in your “Example of Script using CD” example that the XLSWRITE call throws an error for whatever reason (you don’t have permissions to write to the file or directory, XLSWRITE can’t process the information in the variable data, etc.) As written, after the error is thrown you’ll be in the outputDir directory, not currentDir. [While you could avoid this particular problem if you used the onCleanup object introduced in release R2008b, there are other reasons to think carefully before using CD.]
Suppose that you had a specialized file writing command, QUANWRITE, that creates a file in a specific format, and that this function is in your current directory. If you modified your “Example of Script using CD” example to use QUANWRITE, and your current directory is not on your MATLAB path, the script will fail because it can’t find QUANWRITE in your new current directory after the CD.
There’s one circumstance I can think of where “relative” paths are okay and even useful — if you use a path relative to a known location, like MATLABROOT. For instance, many of the MATLAB demo files are located in toolbox/matlab/demos. If I want to edit the logo.m file in that directory, I can use:
The command above works no matter where MATLAB is installed, as long as the directory structure underneath hasn’t been modified. Two “known locations” that are useful as the “root” of a FULLFILE call are MATLABROOT and TOOLBOXDIR (introduced in release R2006a.)
Thanks Steve,
Using the CD command has always gotten me in trouble before, until I learned the goodness of FULLFILE. Thanks for the added comment, as I think it really elaborates on and clarifies what I was trying to say!
Quan
“it’s good practice to use the absolute file path instead of the relative ones as it will make your code more flexible and portable.”
More portable to whom? Someone else who also has to have “C:\output”? What if I want to share the script/function with a friend running Linux, for whom “C:\output” can’t even exist?
On the other hand, consider a script in the current directory, which contains multiple directories, each with data from a different experiment (several files per experiment, which explains the directories). If the script’s written to look for input/output relative to the current directory, then everything still winds up in the right place, even when I send the whole subtree to another machine, or if it’s stored on a portable drive instead of “C:\”.
(Otherwise similar to Steve L’s comment, except that sometimes it’s nice to keep one’s data entirely separate from one’s MATLAB install. Makes backup simpler, for one thing.)
Andrew,
I used “C:/output” as an example of an output directory. For the most part, you’re going to be querying the user for location of the output data (for example, by using the UIGETDIR command), so the output directory will be a dynamic variable.
Quan
It’s funny, I used to do the CD command all the time. I never heard of FULLFILE until this post (or maybe there was another one) but for the longest time I just concatenated two strings containing the two parts of the filename I needed:
e.g.
Quan,
So this post is a tiny bit controversial, since it deals with coding style (which can be quite a personal preference). I appreciate you going straight at it, encouraging a “best practice”.
I must say that I rarely use FULLFILE, but concat strings instead. Maybe I’m old school. But I do fully agree with you about avoiding CD where possible. It has cost me more debugging time than its simpler code has saved, by a lot. My most common file handling method is to use UIGETDIR and UIGETFILE, and then use absolute paths throughout.
Nice post,
Rob
Hi Quan,
I agree, cd-ing in the middle of a script is a bad plan. However, I think that relative paths are really important for portability…
I often find that use of the mfilename command is a useful construct in a particular project’s startup.m file:
This way when I give a project to my colleague, they can run startup.m and it will do the right thing every time. If they need to know how to access other files or directories relative to startupDirectory, then they have the variable available to them.
Andrew
@Andrew
That’s a nice example! Thanks for that crafty bit of code.
Also, to add to what Andrew said. Sometimes, when I create a more complicated MATLAB function, it contains a bunch of subfunctions, which I store into a subfolder. To make sure that these subfunctions can be called, you can do the same thing Andrew did a above and add the paths of these folders wherein these subfunctions are located.
If you have the time, you should track down Daniel Sutoyo and say hello to him over there in Natick.
[...] is useful so that you don’t have to change directories when writing data. See this post on avoiding the CD command for more information on this topic. Make sure that the directory where you want to write to exists, [...]