-
Notifications
You must be signed in to change notification settings - Fork 0
/
getfn.m
38 lines (38 loc) · 1.28 KB
/
getfn.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function filenames = getfn(mydir, pattern)
%GETFN Get filenames in directory and subdirectories.
%
% FILENAMES = GETFN(MYDIR, PATTERN)
%
% Example: Get all files that end with 'txt' in the current directory and
% all subdirectories
%
% fn = getfn(pwd, 'txt$')
%
% [email protected] 2016-07-06
if nargin == 0
mydir = pwd;
end
% computes common variable FILENAMES: get all files in MYDIR and
% recursively traverses subdirectories to get all files in these
% subdirectories:
getfnrec(mydir)
% if PATTERN is given, select only those files that match the PATTERN:
if nargin > 1
idx = ~cellfun(@isempty, regexp(filenames, pattern));
filenames = filenames(idx);
end
function getfnrec(mydir)
% nested function, works on common variable FILENAMES
% recursively traverses subdirectories and returns filenames
% with path relative to the top level directory
d = dir(mydir);
filenames = {d(~[d.isdir]).name};
filenames = strcat(mydir, filesep, filenames);
dirnames = {d([d.isdir]).name};
dirnames = setdiff(dirnames, {'.', '..'});
for i = 1:numel(dirnames)
fulldirname = [mydir filesep dirnames{i}];
filenames = [filenames, getfn(fulldirname)];
end
end % nested function
end