I want to get/search for all of the ".mat" files in an exact directory and all of the subdirectories within. How can I get all of the subdirectories and subfiles to my variables list?
Show older comments
For example, I have the MATLAB root folder, I have ".mat" files there and I have the MAT subfolder where are a lot of ".mat" files as well. After getting the ".mat" files, I want to change their names.
%% Choosing the input file or folder
folder = uigetdir;
% Getting the folders and files
all_files = dir(folder);
all_dir = all_files([all_files(:).isdir]);
num_dir = numel(all_dir);
%% Getting the subfolders and subfiles
for h = 0:num_dir
subfolder = all_dir.name; ???????????
v = genvarname('subfolder', who); ???????????
eval([v ' = dir(subfolder)']) ???????????
subfiles = dir(subfolder); ???????????
subdir = subfiles([subfiles(:).isdir]);
num_subdir = numel(subdir);
end
%% Searching for '.mat' files
matfiles = dir('.mat');
Answers (3)
dpb
on 19 Oct 2015
Simpler way is to use the OS directory search...for Windows
s=uigetdir; % initial subdirectory
[~,d]=dos(['dir /s /b ' fullfile(s,'*.mat')]; % OS dir command
d=textscan(d,'%s','delimiter','\n'); d=d{:}; % convert string to cellstr array
for i=1:length(d)
... % process each file here
Salt to taste as needed for given OS...
Image Analyst
on 19 Oct 2015
0 votes
Use genpath(). And don't use - ever - eval()!
See attached demo code that will do what you ask. Just adapt the file pattern to *.mat. It will recurse into all subfolders and find all mat files in all subfolders.
Jan
on 19 Oct 2015
0 votes
This has been solved frequently in the FileExchange: Search for "file recursive". You find e.g.:
1 Comment
dpb
on 19 Oct 2015
I began submitting enhancement requests along about Version 4 to incorporate the OS switches in dir to no avail as yet...only been 25 yr, more or less... :(
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!