Working With Directories

Playing around within the Matlab ecosystem is fine, as far as that goes, but eventually, you will need to get data in and out, and to do that, you'll have to work with directories. Honestly, this is not a strong point for Matlab, mostly because there are better tools out there (shell scripting). Thankfully, most of what you'll need can be accomplished with a few simple commands (along with the Matlab principles we've been practicing).

Contents

Getting Started

So let's get cracking. First, you'll need to download the zip file from here. Then you'll need to unzip it. I don't care where. Just make sure you note where and that the "Re-create folders" box is checked before you click "Extract."

Now, in Matlab, use the GUI to navigate to the folder where you extracted the zip file. You should be able to see that exampledir is a subfolder. Our goal in this lesson is to practice working with directories.

Simple directory commands

First, let's find out where we are. The pwd command gets the present working directory (get it?).

pwd
ans =

/home/jmp33/Dropbox/matlab class/in-class

We can also assign this to a variable for use later. For instance, we might want to save the directory in which we started so that we can return to it once our processing is done:

original_dir=pwd; %store the answer in a string

You'll get a different answer, but that's okay. It will also depend on what operating system you're using (more on that later). Depending on your screen setup, this will match what's displayed in the location bar beneath the menu and buttons in the GUI.

For our next trick, let's find out what's in our current directory:

dir
.                             function_rules.log            
..                            function_rules.pdf            
L1.m                          function_rules.synctex.gz     
L2.m                          function_rules.tex            
L2_data.mat                   html                          
L2_old.m                      importing_data.m              
L3.m                          index.m                       
L3_data.mat                   jury_data.csv                 
L3_scratch.m                  jury_data.xls                 
L4.m                          jury_data.xlsx                
basic_syntax.m                logical_nan.m                 
capture_problems.m            loop_intro.m                  
cell_arrays.m                 myoutput.mat                  
control_structures_example.m  myscript.m                    
csl.m                         plotting_intro.m              
exampledir                    slice_cookbook.m              
exampledir.zip                structs.m                     
fall11                        summer11                      
fall11.zip                    summer11.zip                  
files_problems.m              testcell.mat                  
function_intro.m              working_with_directories.m    
function_rules.aux            

(We could also have used ls, for those of you used to Linux/Unix.)

Again, you will get somewhat different output, but there are a few things to notice:

Similarly, we can change directories with the cd (change directory) command:

pwd
cd .   %goes nowhere (change to current directory)
pwd    % see?
ans =

/home/jmp33/Dropbox/matlab class/in-class


ans =

/home/jmp33/Dropbox/matlab class/in-class

cd exampledir
pwd
ans =

/home/jmp33/Dropbox/matlab class/in-class/exampledir

cd .. %go back up a directory
pwd
ans =

/home/jmp33/Dropbox/matlab class/in-class

We can also do variations on this:

cd exampledir/subdir1 %jump down two directories (in Windows/replace '/' with '\')
pwd
ans =

/home/jmp33/Dropbox/matlab class/in-class/exampledir/subdir1

cd(original_dir) %go to directory stored in string original_dir
pwd
ans =

/home/jmp33/Dropbox/matlab class/in-class

Saving directory information

The directory command dir is much more powerful than shown above. For instance, we can save the output for fancy processing:

cd('exampledir') %move down a directory
flist=dir; %find all files and folders; save in structure array
numel(flist) %how many were there?
ans =

     5

When we save its output, dir returns a structure with one element for each directory listing. This contains a lot of handy information:

fieldnames(flist)
ans = 

    'name'
    'date'
    'bytes'
    'isdir'
    'datenum'

For us, the key fields will be name, the entry's name, and isdir, a logical indicating whether or not the entry is a directory. And because dir returns a structure array, we can get individual fields by capturing with comma-separated lists.

Problems

  1. Make a variable containing all the values in the name field of flist
  2. Make a logical variable indicating whether each element of flist is a directory or not.

Switching between operating systems

Sometimes, you don't have the luxury of doing all your coding, experimentation, data storage and analysis on the same operating system. When that happens, it's nice to be able to code flexibly.

Matlab gives you a couple of ways to do this:

  1. You can use commands like computer and ismac, ispc, etc. to test for which os you're on and act accordingly.
  2. You can be smart about it. (Confession: I have done the first one a lot.)

But let's try option 2. Let's say we don't know what type of machine we'll be on in advance, or even what directory we're in, but we need an absolute (full) path to a given file. Since dir gives us filenames and pwd gives us directories, we're most of the way there. We just need one more special matlab command to get us home:

filesep
ans =

/

This is a special matlab string that changes based on operating system. On Unix and Mac, it gives '/', while on Windows, it returns '\'. This gets us around the code above, where I had to tell you to replace your slash with a backslash to make it work in Windows.

So what's it good for? Try this:

matfiles=dir('*.mat'); %get a listing of all the .mat files;
matnames={matfiles.name};
wholename=[pwd filesep matnames{1}] %concatenate current directory name and filename into a single string
wholename =

/home/jmp33/Dropbox/matlab class/in-class/exampledir/practice.mat

And best of all, if someone gave us a full filename, we could reverse this process:

[pathstr,fname,ext]=fileparts(wholename)
pathstr =

/home/jmp33/Dropbox/matlab class/in-class/exampledir


fname =

practice


ext =

.mat

Neat, huh?

The key to all of this is that once you're comfortable working with structure arrays (the data returned by dir) and the tools needed to pull data from them, working with directories is no more complicated than any other programming problem.

Further reading

Mathworks Help

what

whos

system