wolffd@0: function filenames = dirKPM(dirname, ext, varargin) wolffd@0: % dirKPM Like the built-in dir command, but returns filenames as a cell array instead of a struct wolffd@0: % wolffd@0: % filenames = dirKPM(dirname) wolffd@0: % returns all files, except '.' and '..' wolffd@0: % wolffd@0: % filenames = dirKPM('images', '*.jpg') wolffd@0: % returns files with this extension wolffd@0: % eg filenames{1} = 'foo.jpg' etc wolffd@0: % wolffd@0: % OPTIONAL ARGUMENTS [default in brackets] wolffd@0: % filenames = dirKPM('images', '', param1, val1, param2, val2, ...) wolffd@0: % wolffd@0: % 'fileType'='image' ['all'] means return files with extension .jpg, .png, .bmp wolffd@0: % wolffd@0: % 'prepend'=1 [0] means preprend folder name to filename wolffd@0: % eg filenames{1} = 'images/foo.jpg' wolffd@0: % wolffd@0: % 'doSort'=1 [1] means sort filenames in ascending alphanumerical order (where possible) wolffd@0: % wolffd@0: % 'doRecurse'=1 [0] recursive dir, apply the same dirKPM call on all wolffd@0: % subfolders (decrease MAXDEPTH option to prevent recursion from branching wolffd@0: % too explosively) wolffd@0: wolffd@0: if nargin < 1, dirname = '.'; end wolffd@0: wolffd@0: if nargin < 2, ext = ''; end wolffd@0: wolffd@0: [fileType, prepend, doSort, doRecurse, MAXDEPTH, DEPTH] = process_options(... wolffd@0: varargin, 'fileType', 'all', 'prepend', 0, 'doSort', 1, 'doRecurse', 0,... wolffd@0: 'MAXDEPTH', 3, 'DEPTH', 0); wolffd@0: wolffd@0: tmp = dir(fullfile(dirname, ext)); wolffd@0: [filenames I] = setdiff({tmp.name}, {'.', '..'}); wolffd@0: tmp = tmp(I); wolffd@0: wolffd@0: if doRecurse && sum([tmp.isdir])>0 && DEPTH0 wolffd@0: filenames(nfilenames+1:nfilenames+length(subDirFilenames)) = subDirFilenames; wolffd@0: end wolffd@0: end wolffd@0: end wolffd@0: wolffd@0: nfiles = length(filenames); wolffd@0: if nfiles==0 return; end wolffd@0: wolffd@0: switch fileType wolffd@0: case 'image', wolffd@0: for fi=1:nfiles wolffd@0: good(fi) = isImage(filenames{fi}); wolffd@0: end wolffd@0: filenames = filenames(find(good)); wolffd@0: case 'all', wolffd@0: % no-op wolffd@0: otherwise wolffd@0: error(sprintf('unrecognized file type %s', fileType)); wolffd@0: end wolffd@0: wolffd@0: if doSort wolffd@0: % % sort filenames alphanumerically (if possible) wolffd@0: % DJE, buggy, MUST save tmp.anr/snr/str or else we potentially lose wolffd@0: % filenames wolffd@0: % tmp = asort(filenames, '-s', 'ascend'); wolffd@0: % if ~isempty(tmp.anr) wolffd@0: % filenames = tmp.anr'; wolffd@0: % else wolffd@0: % filenames = tmp.str'; wolffd@0: % end wolffd@0: % if names could not be sorted, return original order wolffd@0: wolffd@0: filenames=sort(filenames); wolffd@0: wolffd@0: end wolffd@0: wolffd@0: wolffd@0: if prepend wolffd@0: nfiles = length(filenames); wolffd@0: for fi=1:nfiles wolffd@0: filenames{fi} = fullfile(dirname, filenames{fi}); wolffd@0: end wolffd@0: end wolffd@0: