Matlab LogoThe 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?

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.