How to save different mat files from different folders in a cell array

3 次查看(过去 30 天)
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 .

采纳的回答

Mohith Kulkarni
Mohith Kulkarni 2020-11-27
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 个评论
Mohith Kulkarni
Mohith Kulkarni 2020-11-30
编辑:Mohith Kulkarni 2020-11-30
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Standard File Formats 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by