changing file path in a loop

17 views (last 30 days)
Mostafa
Mostafa on 19 Mar 2016
Hi All,
I am trying to import data from different folders in a loop. I have the data in a folder called "Spring 2016 DATA", inside this folder are individual folders for each subject. So there is a "subject1", "subject2".....etc.
I would like to create a loop such that it would go to the subject 1 folder and import that data. Then after it finishes analysis, it would start again and import subject 2 and so on.
My problem is how would I do that using the cd command. Right now I am trying to do the following
cd('C:\Documents\MATLAB\Spring 2016 DATA\..........');
As you can see, I do not know what I can do to replace the ........ and get the rest of the path. I've tried a lot of different options with an error every time. When I place the .........with folder1, it works but I want to change the folder name every time it goes through the loop. Sounds too easy for anyone who knows what they are doing.
Any suggestions would be appreciated.
Thanks in advance.
Mostafa

Answers (2)

Jan
Jan on 19 Mar 2016
Edited: Jan on 19 Mar 2016
Prefer absolute file names instead of changing the current directory:
BasePath = 'C:\Documents\MATLAB\Spring 2016 DATA';
DirList = dir(BasePath);
DirList = DirList([Dirlist.isdir]); % Folders only
for iDir = 1:numel(DirList)
aDir = fullfile(BasePath, DirList(iDir).name);
fprintf('Processing: %s\n', aDir);
...
end
  4 Comments
Image Analyst
Image Analyst on 4 May 2018
Should have been DirList, not Dirlist. Anyway, try this more robust version:
BasePath = 'C:\Program Files\MATLAB\R2018a'; % Wherever you want
% Warn user if there is no such folder.
if ~exist(BasePath, 'dir')
message = sprintf('This folder does not exist:\n%s', BasePath);
uiwait(errordlg(message));
return;
end
% Get a list of all files, including folders.
DirList = dir(BasePath);
% Extract only the folders, not regular files.
DirList = DirList([DirList.isdir]); % Folders only
% Get rid of first two folders: dot and dot dot.
DirList = DirList(3:end);
% Warn user if there are no subfolders.
if isempty(DirList)
message = sprintf('This folder does not contain any subfolders:\n%s', BasePath);
uiwait(errordlg(message));
return;
end
% Count the number of subfolders.
numberOfFolders = numel(DirList);
% Loop over all subfolders, processing each one.
for k = 1 : numberOfFolders
thisDir = fullfile(BasePath, DirList(k).name);
fprintf('Processing folder %d of %d: %s\n', ...
k, numberOfFolders, thisDir);
end
Hypolite Richardson
Hypolite Richardson on 5 May 2018
Thanks Image Analyst...
That piece of code makes life alot easier.
Hypolite

Sign in to comment.


alireza cheraghinezhad
alireza cheraghinezhad on 29 Mar 2018
Thanks, These codes are very helpful.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!