Subfolders file search and allocation
199 views (last 30 days)
Show older comments
I have simulation results of 40 folders (Just an example number) for 40 time steps. Each folder contains some 50 results files. Results files in each folders are same but with different values. I need to allocate A{1} = First file from folder one A{2} = Second file from folder one. so B{1} = first file from folder two and so on...It will be easy for me to concatenate all the similar files.
Just I know how to find a particular file from all the sub folders and allocate it as per requirement.
filetofind = 'Temperature_Wall1.csv';
dirinfo = dir();
dirinfo(~[dirinfo.isdir]) = []; %remove non-directories
tf = ismember( {dirinfo.name}, {'.', '..'});
dirinfo(tf) = []; %remove current and parent directory.
numsubdir = length(dirinfo);
lastmod = inf(numsubdir,1);
for K = 1 : numsubdir
A{K}=load(fullfile(dirinfo(K).name, filetofind));
end
But if i use above commands, I need to mention all the 50 results files names and repeat the coding 50 times. Can someone help me out in shorting it out?
0 Comments
Answers (1)
Jan
on 20 Dec 2017
Do you have a modern Matlab version >= R2016b? Then you can run a recursive search:
Folder = cd;
FileList = dir(fullfile(Folder, '**', '*.csv'))
Now you can use FileList(k).folder and FileList(k).name to import the file's contents to a cell array, maybe a nested cell to have all files with the same name, or with the same folder together.
2 Comments
Jan
on 20 Dec 2017
2013b did not have a recursive dir(). But you find a lot of implementations in the FileExchange: search for "dir recursive".
Unfortunately I cannot elaborate the "FileList(k)" option in detail, because I do not understand what you exactly want as output. But I would never use "A", "B", "C", ... as list of variables, because it is a mess to use this later.
I suggest to download a recursive dir() from the FileExchange. Then step through the files one by one and store the data like:
for iFile = 1:numel(File)
A{iFile, 1} = load(File{iFile});
[A{iFile, 2}, A{iFile, 2}] = fileparts(File{iFile});
end
Now in the 2nd and 3rd column of the cell array A you have the folder and filename. I assume with unique you should find all rows, which belong to each other.
Simply try it and come back, if you get specific problems.
See Also
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!