folder in a directory

How do you use dir to obtain the names of folders in a directory. I can use
files = dir('*.xls');
to obtain information on the excel files within a specified directory but I have a directory which has 4 folders by using dir I obtain the names of each of the files, how is it possible to save the name of each file so that I can refer to each older within a loop.
cheers

 Accepted Answer

Junaid
Junaid on 1 Dec 2011
A = dir % you get everything in current directly of matlab. or if you want to explicitly mention any directory path then you can do it like this.
A = dir('/yourpath');
now A has all files and directories. So you can access by loop
A(1).name
to get only Directory indexes you can do following code.
myDir = find(vertcat(A.isdir));
now myDir has indexes of directory(folders only).
to print the name of directory to confirm, you can do it like this.
A(myDir).name
where first two are only the pointers. you can always start your loop from 3. Ignore first two indexes.

1 Comment

Junaid
Junaid on 1 Dec 2011
I updated the code, to display the name of Directors, last line should be
A(myDir).name

Sign in to comment.

More Answers (1)

It's perhaps worth noting that 'folder' and 'directory' mean the same thing. Anyway, do you want something like this:
files = dir; % assume starting from current directory
filenames = {files.name};
subdirs = filenames([files.isdir]);
for s = 1:length(subdirs)
subdir = subdirs{s};
% process subdirectory
disp(subdir); % for example
end

5 Comments

ricco
ricco on 1 Dec 2011
Thank you. Why is it that when using:
files = dir; % assume starting from current directory
filenames = {files.name};
files returns a 6x1 struct when there are only 4 folder. The first is given as '.' and the second as '..' and then it goes on to naminf the folders!
'.' is the current directory. '..' is the parent of the current directory (the directory that contains the current directory).
ricco
ricco on 1 Dec 2011
many thanks. In addition, do you know how I would use dir('*.xls') in the same context.
So, I now have
path='E:\Practice';
folder = path;
dirListing = dir(folder);
for i=1:length(dirListing);
Data{i}=dirListing(i,1).name;
f{i} = fullfile(path, Data{i});
end
So, 'f' has the path for each of the folders; how could I then find the number of .xls files in each 'f'. I know you can use
files = dir('*.xls');
to find the number of .xls files in a directory but how would you find the number of files in different directories (giuven by 'f')?
ricco
ricco on 1 Dec 2011
I've attempted:
for i=1:length(f)
files(i)=dir(fullfile(path,f(i),'*.xls'));
end
but an error appears!
ricco
ricco on 1 Dec 2011
works now.
for i=1:length(f)
files{i}=dir(fullfile(f{i},'*.xls'));
end
thanks for your help.

Sign in to comment.

Categories

Tags

Asked:

on 1 Dec 2011

Community Treasure Hunt

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

Start Hunting!