0

I have function in matlab (with a wrapper that actualy calls the function) that recursively finds all the .mat files in a given HDD on the computer. On every return it gives the files present in a specific folder, so since theres hundreds of folders on the drive (organized by date) there are hundreds of returns.

I'm trying to make one list (or matrix) of these files so that another script can use this list to do it's job.

The actual return is a list of structures (with fields containing file information). The returns are always one wide and a length depending on how many files are in the folder.

In short, I'd like to know how to take all the returns of a recursive function and put them into one list/matrix.

Any tips would be appreciated! Thank you

function direc = findDir(currentDir)

dirList = dir(currentDir);
if 2 == length(dirList)
    direc = currentDir
    files = dir([currentDir '*.mat'])


    return 
end

dirList = dirList(3:length(dirList));
fileListA = dir([currentDir '*.mat']);

if 0==isempty(fileListA)
    direc = currentDir
    files = dir([currentDir '*.mat'])


    return 

end

for i=1:length(dirList)
    if dirList(i).isdir == 1

        [currentDir dirList(i).name '\'];

        findDir([currentDir  dirList(i).name '\']);

end

end


end
jdrudds
  • 1
  • 1
  • Please clarify what your question is, and post the relevant code you use. To do it, edit your question – Luis Mendo Oct 10 '14 at 19:48
  • 1
    Maybe you are looking for something like [this](http://stackoverflow.com/a/2654459/1586200). It is easy to modify for a particular kind of file, in your case, `.mat`. – Autonomous Oct 10 '14 at 20:17

1 Answers1

0

You can use filesttrib, which searches for all files recursively and outputs a structure array with information about those files. You then remove folders, and keep only files whose name ends in '.mat'.

To check if the file name ends in '.mat', use regexp. Note that a direct comparison like name(end-3:end)=='.mat' will fail if the string name is too short.

currentDir = 'C:\Users\Luis\Desktop'; %// define folder. It will be recursively 
%// searched for .mat files
[~, f] = fileattrib([currentDir '\*']); %// returns a structure with information about
%// all files and folders within currentDir, recursively
fileNames = {f(~[f.directory]).Name}; %// remove folders, and keep only name field
isMatFile = cellfun(@(s) ~isempty(regexp(s, '\.mat$')), fileNames); %// logical index
%// for mat files
matFileNames = fileNames(isMatFile);

The variable matFileNames is a cell array of strings, where each string is the full name of a .mat file.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147