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
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
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 Center 및 File Exchange에서 Standard File Formats에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!