Borealis
Borealis

Reputation: 8480

Subset folder contents Matlab

I have about 1500 images within a folder named 3410001ne => 3809962sw. I need to subset about 470 of these files to process with Matlab code. Below is the section of code prior to my for loop which lists all of the files in a folder:

workingdir = 'Z:\project\code\';  
datadir = 'Z:\project\input\area1\';     
outputdir = 'Z:\project\output\area1\';   

cd(workingdir) %points matlab to directory containing code

files = dir(fullfile(datadir, '*.tif'))
fileIndex = find(~[files.isdir]);
for i = 1:length(fileIndex)
    fileName = files(fileIndex(i)).name;

Files also have ordinal directions attached (e.g. 3410001ne, 3410001nw), however, not all directions are associated with each root. How can I subset the folder contents to include 470 of 1500 files ranging from 3609902sw => 3610032sw? Is there a command where you can point Matlab to a range of files in a folder, rather than the entire folder? Thanks in advance.

Upvotes: 0

Views: 294

Answers (2)

Amro
Amro

Reputation: 124563

Consider the following:

%# generate all possible file names you want to include
ordinalDirections = {'n','s','e','w','ne','se','sw','nw'};
includeRange = 3609902:3610032;
s = cellfun(@(d) cellstr(num2str(includeRange(:),['%d' d])), ...
    ordinalDirections, 'UniformOutput',false);
s = sort(vertcat(s{:}));

%# get image filenames from directory
files = dir(fullfile(datadir, '*.tif'));
files = {files.name};

%# keep only subset of the files matching the above
files = files(ismember(files,s));

%# process selected files
for i=1:numel(files)
    fname = fullfile(datadir,files{i});
    img = imread(fname);
end

Upvotes: 3

Not Bo Styf
Not Bo Styf

Reputation: 411

Something like this maybe could work.

list = dir(datadir,'*.tif'); %get list of files
fileNames = {list.name}; % Make cell array with file names
%Make cell array with the range of wanted files. 
wantedNames = arrayfun(@num2str,3609902:3610032,'uniformoutput',0); 

%Loop through the list with filenames and compare to wantedNames.

for i=1:length(fileNames)
% Each row in idx will be as long as wantedNames. The cells will be empty if 
% fileNames{i} is unmatched and 1 if match.
   idx(i,:) = regexp(fileNames{i},wantedNames);
end
idx = ~(cellfun('isempty',idx)); %look for unempty cells.
idx = logical(sum(,2)); %Sum each row

Upvotes: 1

Related Questions