How to change the directory in the middle of a code

3 views (last 30 days)
Dear All MATLAB Users :-)
I have a critical question whose answer will save much time for me. Well basically the answer to my question will increase my ability of running as many as calculations I need during my sleep hours :-)
Assume on my desktop I have 4 folders ( directories ). Each of them is containing of many text files. The names of these directories are 1,2,3 and 4 respectively.
Now I have a code (m-file) located in each of these sub directories. Obviously once the code is run, all calculation will be performed on the files within that directory. What I basically seek for is a way to change the directory address after calculations for the files located in folder 1 finish. As a result, by running my code once, all of the folders will be covered one after another.
% THE CODE START RUNNING WITHIN THE DIRECTORY 1
for k = 1:50 % NUMBER OF TEXT FILES IN THE FIRST DIRECTORY
filename = sprintf('%d.txt',k);
A = load(filename);
% doing some calculations
print the output for k.txt
end
% THIS IS WHAT i WANT : Change the directory to the second one and again start running the code for the text files in the second folder.
for k = 1:10
filename = sprintf('%d.txt',k);
A = load(filename);
% doing some calculations
print the output for k.txt
end
Thank you in advanced. Best, HRJ

Answers (1)

Image Analyst
Image Analyst on 31 Aug 2015
Try it this way:
topLevelFolder = 'C:/myData/whatever'; % Forward slashes works with Windows too!
for f = 1 : 4
% Get the name of this folder.
thisFolder = sprintf('topLevelFolder/%d', f);
% See if it actually exists
if ~isdir(thisFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', thisFolder);
uiwait(warndlg(errorMessage));
continue;
end
% Get a list of the .mat files in thisFolder.
filePattern = fullfile(thisFolder, '*.mat');
matFiles = dir(filePattern);
for k = 1:length(matFiles)
baseFileName = matFiles(k).name;
fullFileName = fullfile(thisFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Read it in
storedStructure = load(fullFileName);
% Do some operations.
end
end
  3 Comments
Homayoon
Homayoon on 31 Aug 2015
well unfortunately i always receive such an error message :
The following folder does not exist:topLevelFolder
Walter Roberson
Walter Roberson on 31 Aug 2015
Edited: Walter Roberson on 31 Aug 2015
The line
thisFolder = sprintf('topLevelFolder/%d', f);
should have been
thisFolder = fullfile(topLevelFolder, sprintf('%d', f));

Sign in to comment.

Categories

Find more on Search Path in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!