How to change the directory in the middle of a code
조회 수: 2 (최근 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에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!