Ping Lou
Ping Lou

Reputation: 13

matlab multiple folders

I have one dir with 50 folders, and each folder has 50 files. I have a script to read all files in each folder and save the results, but I need to type the folder name every time. Is there any loop or batch tools I can use? Any suggestions or code greatly appreciated.

Upvotes: 1

Views: 2504

Answers (1)

ackrause
ackrause

Reputation: 442

There may be a cleaner way to do it, but the output of the dir command can be assigned to a variable. This gives you a struct, with the pertinent fields being name and isdir. For instance, assuming that the top-level directory (the one with 50 files) only has folders in it, the following will give you the first folder's name:

folderList = dir();
folderList(3).name

(Note that the first two entries in the folderList struct will be for "." (the current directory) and ".." (the parent directory), so if you want the first directory with files in it you have to go to the third entry). If you wish to go through the folders one by one, you can do something like the following:

folderList = dir();
for i = 3:length(folderList)
    curr_directory = pwd;
    cd(folderList(i).name); % changes directory to the next working directory
    % operate with files as if you were in that directory
    cd(curr_directory);  % return to the top-level directory
end

If the top-level directory contains files as well as folders, then you need to check the isdir of each entry in the folderList struct--if it is "1", it's a directory, if it is "0", it's a file.

Upvotes: 5

Related Questions