Loading variables from different folders containing subfolders in loop

1 view (last 30 days)
I have 39 folders, each of them containing 6 subfolders with mat files inside in the form of a matrix mxn. From the matfiles, I need to load the matrices with the lowest n of zeros in a loop and save them in a mat.file in the workspace so that those can be loaded when it is necessary to save variables in them.
Any suggestion on how to do that?
Thank you!

Sign in to comment.

Accepted Answer

Mathieu NOE
Mathieu NOE on 20 Jan 2022
an example below to show how to loop over directories and load in natural sorting ordre the files in each folder
%% define path
yourpath = pwd; % or your specific path
list=dir(yourpath); %get info of files/folders in current directory
isfile=~[list.isdir]; %determine index of files vs folders
dirnames={list([list.isdir]).name}; % directories names (including . and ..)
dirnames=dirnames(~(strcmp('.',dirnames)|strcmp('..',dirnames))); % remove . and .. directories names from list
%% demo for excel files
sheet = 1; % specify which sheet to be processed (my demo) - if needed
%% Loop on each folder
for ci = 1:length(dirnames) %
fileDir = char(dirnames(ci)); % current directory name
S = dir(fullfile(fileDir,'Sheeta*.xlsx')); % get list of data files in directory according to name structure 'Sheeta*.xlsx'
S = natsortfiles(S); % sort file names into natural order (what matlab does not) , see FEX :
%% Loop inside folder
for k = 1:length(S) % read data in specified sheet
data = xlsread(fullfile(fileDir, S(k).name),sheet); % or use a structure (S(k).data ) to store the full data structure
% your own code here for data processing. this is just for my demo
% for now :
title_str = [fileDir ' / ' S(k).name ' / sheet : ' num2str(sheet)];

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!