How to save different mat files from different folders in a cell array
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Abdulhakim Alezzi
il 23 Nov 2020
Commentato: Abdulhakim Alezzi
il 30 Nov 2020
Hi friends,
I have 51 folders named with (copy_1, copy_2, copy_3 ..... copy_51). Each folder of these has 25 matfiles (X1, X2,X3...X25).
1- I want to concatenate all the matflies (25 matfiles) from each folder (51 folders) in cell array. The output cell will be (1275 * 1). I just want to save them like the attached picture.
i have tried this code, but it does not help me.
D = 'path to the folder where the files are saved'
S = dir(fullfile(D,'X*.mat'));
C = cell(1,numel(S));
Z = load(fullfile(D,S(1).name));
F = fieldnames(T);
for k = 2:numel(S)
T = load(fullfile(D,S(k).name));
for n = 1:numel(F)
Z.(F{n}) = cat(1, Z.(F{n}), T.(F{n}));
end
end
save(fullfile(D,'Y.mat'),'Z')
....
Any help will be highly appreciated .
Risposta accettata
Mohith Kulkarni
il 27 Nov 2020
If the goal is to store each mat file in a separate cell with the data of the variables each of the mat files concatenated into one cell, refer to the code below:
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);
out = cell(1275,1); % initialize the empty cell array.
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
for n = 1:numel(thisfile)
out{(D-1)*25 + F,1} = cat(1,out{D*F},file_struct.(thisfile{n}));
end
end
end
4 Commenti
Mohith Kulkarni
il 30 Nov 2020
Modificato: Mohith Kulkarni
il 30 Nov 2020
Try the following instead as the data is being copied from each variable of the mat file, "fieldnames" is used to access the variables :
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
Fields = fieldnames(file_struct);
for n = 1:numel(Fields)
out{(D-1)*25 + F,1} = cat(1,out{(D-1)*25 +F,1},file_struct.(Fields{n}));
end
end
end
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Standard File Formats in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!