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?
古いコメントを表示
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');
回答 (3 件)
dpb
2015 年 10 月 19 日
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
2015 年 10 月 19 日
0 投票
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
2015 年 10 月 19 日
0 投票
This has been solved frequently in the FileExchange: Search for "file recursive". You find e.g.:
1 件のコメント
dpb
2015 年 10 月 19 日
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... :(
カテゴリ
ヘルプ センター および File Exchange で Search Path についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!