MATLAB: Problem with “change directory” in a for loop

cannot cdcdchange directoryfor loop

I'm having a problem with "cd" when looping through folders. Below is the problematic part of my script:
datadir='wherethedatais';
cd(datadir);
dirlist=dir('sub*'); % list of different subjects
for h=1:length(dirlist)
cd(dirlist(h).name)
Everything is fine until the 7th iteration of the loop when I get this error:
Error using cd
Cannot CD to sub0010 (Name is nonexistent or not a directory).
All the folders are named subXXXX where XXXX is 0001 to 0114.
Any ideas what might be causing this?

Best Answer

Using cd just to read data is error prone. Because you have to ensure that after cd to change back to your original dir, otherwise the next dir will not be found. So if you first change to sub001, then the next change to sub002 will work from within sub001, i.e., tries to change to sub001/sub002 with respect to your original dir.
Instead of cd, use something like
filename = fullfile(dirlist(h).name, 'data.mat')); %assuming 'data.mat' is the name of your mat-file in the various subdirectories
load(filename, 'X'); % assuming 'X' is the variable you need from file data.mat
Related Question