How to change the directory in the middle of a code
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Image Analyst
2015-8-31
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 个评论
Walter Roberson
2015-8-31
编辑:Walter Roberson
2015-8-31
The line
thisFolder = sprintf('topLevelFolder/%d', f);
should have been
thisFolder = fullfile(topLevelFolder, sprintf('%d', f));
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Search Path 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!