MATLAB: Load files from different folders in current folder

folderopen

Hello
I have 3 different folders in the current folder (CBC, MHA, FJR). Each folder contains 12 mat files which have the same names in all folders. I have some code, that load and make some data processing on 12 files from one folder. Now I want to make a for loop that perform data processing in all three folders. I would like something like open the folder, make data processing and go back to current folder, then open another folder and so on. How can I do that?

Best Answer

projectdir = '.'; %or name of containing folder
foldinfo = dinfo(projectdir);
foldinfo(~[foldinfo.isfolder]) = []; %get rid of non-folders
foldinfo(ismember({foldinfo.name}, {'.', '..'})) = []; %get rid of . and .. folders
foldnames = fullfile(projectdir, {foldinfo.name});
numfold = length(foldnames);
for D = 1 : numfold
thisfold = foldnames{D};
dinfo = dir( fullfile(thisfold, '*.mat'));
filenames = fullfile(thisfold, {dinfo.name});
numfile = length(filenames);
for F = 1 : numfile
thisfile = filenames{F};
file_struct = load(thisfile);
%now extract variables from file_struct and process them
end
end