Loading variables from different folders containing subfolders in loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Eleonora Montagnani
el 19 de En. de 2022
Comentada: Eleonora Montagnani
el 20 de En. de 2022
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 comentarios
Stephen23
el 20 de En. de 2022
Editada: Stephen23
el 20 de En. de 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.
Respuesta aceptada
Mathieu NOE
el 20 de En. de 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
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre File Operations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!