changing file path in a loop
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (2)
Jan
el 19 de Mzo. de 2016
Editada: Jan
el 19 de Mzo. de 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 comentarios
Image Analyst
el 4 de Mayo de 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
el 5 de Mayo de 2018
Thanks Image Analyst...
That piece of code makes life alot easier.
Hypolite
Ver también
Categorías
Más información sobre Convert Image Type en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!