MATLAB: FAQ: How to process a sequence of files

faqfaq_loopoverfilesfaqlistloopprocess files

How can I process a sequence of files?

Best Answer

If the files that you want to process are sequentially numbered, like "file1.txt", "file2.txt", "file3.txt", etc. then you can use SPRINTF or NUM2STR to create the filename and LOAD, IMREAD, FOPEN, etc. to retrieve the data from the file. (Also note the three different ways of building the filename - you can use your favorite way.)
% Read files file1.txt through file20.txt, mat1.mat through mat20.mat
% and image1.jpg through image20.jpg. Files are in the current directory.
folder = cd;
for k = 1:20
matFilename = sprintf('mat%d.mat', k);
matData = load(fullfile(cd, matFilename));
jpgFilename = sprintf('image%d.jpg', k);
imageData = imread(jpgFilename);
textFilename = sprintf('file%d.txt', k);
fid = fopen(fullfile(folder, textFilename), 'rt');
textData = fread(fid);
fclose(fid);
end
In the above code, matData, imageData, and textData will get overwritten each time. You should save them to an array or cell array if you need to use them outside the loop, otherwise use them immediately inside the loop.
If instead you want to process all the files whose name matches a pattern in a directory, you can use DIR to select the files. Note that while this example uses *.jpg as the pattern and IMREAD to read in the data, as with the previous example you could use whatever pattern and file reading function suits your application's needs:
Folder = 'C:\Documents and Settings\yourUserName\My Documents\My Pictures';
if exist(Folder, 'dir') ~= 7 % isfolder(Folder) in modern Matlab versions
Message = sprintf('Error: The following folder does not exist:\n%s', Folder);
uiwait(warndlg(Message));
return;
end
filePattern = fullfile(Folder, '*.jpg');
jpegFiles = dir(filePattern);
for k = 1:length(jpegFiles)
baseFileName = jpegFiles(k).name;
fullFileName = fullfile(Folder, baseFileName);
fprintf('Now reading %s\n', fullFileName);
imageArray = imread(fullFileName);
imshow(imageArray); % Display image.
drawnow; % Force display to update immediately.
end
[EDITED] With modern Matlab versions (I assume since at least R2016b):
You can use '**' for a recursive search, if the files are in multiple subfolders:
Folder = 'C:\Your\Folder';
FileList = dir(fullfile(Folder, '**', '*.jpg'));
for iFile = 1:numel(FileList)
thisFolder = FileList(iFile).folder;
thisFile = FileList(iFile).name;
File = fullfile(thisFolder, thisFile);
... Import the File now as you need...
end
Or you can try a "File Exchange Pick of the Week": FileExchange: FileFun.
This answer is a modified version of: