MATLAB: Directory Issue – not finding subfolder

directorydirectory mappingextracting dataMATLAB

Hi,
(Note: all subfolders and the subfolders' subfolders are on the search path).
I'm currently mapping and extracting data from different folders. I've mapped the present working directory, and its subfolders'. However, when i try to map the subfolders subfolders using dir, i get a message saying that the specific folders are not found. However, if i click the subfolder and attempt to run dir to map the subsubfolder, it works. I need to run this code for a large scale of folders, so clicking each subfolder and running dir by hand is not feasible.
eg NSW -> 2018 -> April 2018 -> file i need to extract.
dir('2018') works, but dir('April 2018') does not work, unless i click into the 2018 folder.
If i change the current directory to 2018 (ie cd 2018), then dir('April 2018') works. However, i need to change the cd back to the parent NSW directory if i use this method, which i haven't been able to figure out how to do.
Any advice on how to approach this issue is appreciated. Apologies if this question has been asked before, but i could not find an answer looking at previous posts.
If i've been unclear, i will clarify any area.
Cheers,
Kiran

Best Answer

"Any advice on how to approach this issue is appreciated."
Either use dir or sprintf to suit your requirements, e.g. (untested, but should get you started):
P = 'path of the root directory'
S = dir(fullfile(P,'*'));
Q = setdiff({S([S.isdir]).name},{'.','..'});
for ii = 1:numel(Q) % loop over subfolders.
S = dir(fullfile(P,Q{ii},'*'));
R = setdiff({S([S.isdir]).name},{'.','..'});
for jj = 1:numel(R) % loop over subsubfolders.
S = dir(fullfile(P,Q{ii},R{jj},'*.txt'));
for kk = 1:numel(S) % loop over files.
F = fullfile(P,Q{ii},R{jj},S(kk).name); % Filename
... process your file
end
end
end
See also:
and many threads that discuss looping over subfolders, e.g.:
etc.
And also: