Loading variables from different folders containing subfolders in loop

조회 수: 1 (최근 30일)
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
Stephen23
Stephen23 2022년 1월 20일
편집: Stephen23 2022년 1월 20일
@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.

댓글을 달려면 로그인하십시오.

채택된 답변

Mathieu NOE
Mathieu NOE 2022년 1월 20일
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개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by