MATLAB Answers

Lewis
0

cannot iterate over subdirectories from data structure

Asked by Lewis
on 3 Oct 2017
Latest activity Edited by Stephen Cobeldick on 3 Oct 2017
Hi. I'm trying to create an array of subdirectories that I can then iterate over and perform some function within. Despite browsing the forums I can't seem to find a simple example of this that I can use.
Here is where I've got to:
raw_directory = 'F:\L\raw_data';
raw_structure = dir(raw_directory);
% get the directories only
isDir = [raw_structure.isdir];
raw_foldernames = {raw_structure(isdir).name};
That's great, now I can see my folders and index into whatever ones I want. Now I want to write a loop that goes into each directory and performs a function on all of the files.
Since the first 2 folders are '.' and '..', the actual folder is at position 3. But when I try to create a data structure for that I get an error:
x = dir(raw_foldernames(3))
Error using dir
Function is not defined for 'cell' inputs.
I've tried a few other things but nothing is working and would appreciate some help.

  0 Comments

Sign in to comment.

1 Answer

Answer by Stephen Cobeldick on 3 Oct 2017
Edited by Stephen Cobeldick on 3 Oct 2017
 Accepted Answer

You need use cell array indexing with a cell array, and generate the full path using fullfile. Note that . and .. are not guaranteed to be the first two names, and so you should remove them using setdiff or the like:
raw_directory = 'F:\L\raw_data';
raw_structure = dir(raw_directory);
raw_foldernames = {raw_structure([raw_structure.isdir]).name};
raw_foldernames = setdiff(raw_foldernames,{'.','..'});
...
F = fullfile(raw_directory,raw_foldernames{1}) % note {} not ()
S = dir(F)

  0 Comments

Sign in to comment.