How to combine the multiple .mat files of ecg to get a single file.
3 views (last 30 days)
Show older comments
I have 23 files(in .mat) of atrial fibrillation database. i want to combine all these mat files to get a matrix of (23*2500) where 2500 is the samples of each .mat files and 23 is the no of records or no. of files.
Please help!
2 Comments
Accepted Answer
Stephen23
on 19 Oct 2020
Edited: Stephen23
on 19 Oct 2020
This should get you started:
D = 'path to the folder where the files are saved';
S = dir(fullfile(D,'*.mat'));
for k = 1:numel(S)
F = fullfile(D,S(k).name);
T = load(F);
S(k).data = T.val;
end
M = vertcat(S.data);
save(fullfile(D,'merged.mat'),'M')
4 Comments
Stephen23
on 19 Oct 2020
"Reference to non-existent field 'val'."
Your uploaded .mat file contains one variable named val, so I assumed that every file has the same variable name (answering your question is a lot easier if you give this kind of information, then we don't have to guess important details like this).
Here is a simple adaption of my answer that will work regardless of the variable name, it assumes that each .mat file contains exactly one variable. Replace the two lines with T in them with these two:
C = struct2cell(load(F));
S(k).data = C{1};
More Answers (1)
Image Analyst
on 19 Oct 2020
Try this:
folder = pwd; %'path to the folder where the files are saved';
fileList = dir(fullfile(folder, '*.mat'));
numFiles = numel(fileList);
fileCounter = 0;
allValData = [];
for k = 1 : numFiles
fullFileName = fullfile(folder,fileList(k).name);
% Skip output file if it already exists.
if contains(fullFileName, 'allValData.mat', 'IgnoreCase', true)
continue;
end
fprintf('Reading %s (#%d of %d)...\n', fullFileName, k, numFiles);
storedStructure = load(fullFileName);
% If storedStructure has a field called val, concatenate it.
if isfield(storedStructure, 'val')
allValData = [allValData; storedStructure.val];
fileCounter = fileCounter + 1;
else
fieldnames(storedStructure) % Report what fields there are to the command window.
warningMessage = sprintf('WARNING : There is no Val field in file %d of %d:\n%s', k, numFiles, fullFileName);
fprintf('%s\n', warningMessage);
promptMessage = sprintf('%s\nDo you want to Continue processing,\nor Quit processing?', warningMessage);
titleBarCaption = 'Continue?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Continue', 'Quit', 'Continue');
if contains(buttonText, 'Quit', 'IgnoreCase', true)
break;
end
end
end
fprintf('Concatenated %d of %d files. Skipped %d files.\n', fileCounter, numFiles, numFiles - fileCounter);
fullOutputFileName = fullfile(folder, 'allValData.mat');
save(fullOutputFileName, 'allValData')
Did it work, or if not, did you see anything unusual?
0 Comments
See Also
Categories
Find more on Signal Generation and Preprocessing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!