Loading variables from different folders containing subfolders in loop

1 view (last 30 days)
Hello,
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!
  4 Comments
Stephen23
Stephen23 on 20 Jan 2022
Edited: Stephen23 on 20 Jan 2022
@Eleonora Montagnani: it sounds like you probably just need to store the imported data in an array. One approach is to use a cell array, as shown in the MATLAB documentation:
Another simple and versatile approach is to use the structure returned by DIR:
P = 'absolute or relative path to the root directory',
S = dir(fullfile(P,'**','*.mat'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
D = load(F);
.. decide what data you want to store
S(k).somedata = whatever_you_want_to_store;
S(k).otherdata = something_else;
end
Then you can use another loop to compare those matrices and perform your analyses.

Sign in to comment.

Accepted Answer

Mathieu NOE
Mathieu NOE on 20 Jan 2022
hello
an example below to show how to loop over directories and load in natural sorting ordre the files in each folder
clc
clearvars
%% 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 :
%(https://fr.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort)
%% 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)];
figure,plot(data),title(title_str);
end
end

More Answers (0)

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!