MATLAB Answers

How to load multiple .mat files containing timetables into the workspace and concatenate them vertically

11 views (last 30 days)
Oliver Higbee
Oliver Higbee on 3 Sep 2021
Edited: Stephen on 4 Sep 2021
Hi there,
I'm trying to load ~100 .mat files into the workspace and combine them into a single timetable.
Each file contains a timetable from a specific date and I'm simply trying to combine them together. However I'm struggling to not name them dynamically.
clearvars
matFiles = dir('*.mat');
numfiles = length(matFiles);
mydata = cell(1, numfiles);
for k = 1:numfiles
mydata{k} = load(matFiles(k).name);
end
This produces a 1x100 cell array, where each cell is a 1x1 struct containing a timetable. However when they are loaded in, the struct fieldname is taken from the filename which means they are all different and I cannot use vertcat. (I.e. I get 'Names of fields in structure arrays being concatenated do not match' error). Do I have to rename the structs and if so how or have I gone about this all wrong?
What is the correct way to process this sequence of files?
Kind regards,
Oliver
  3 Comments

Sign in to comment.

Accepted Answer

Stephen
Stephen on 4 Sep 2021
Edited: Stephen on 4 Sep 2021
"Do I have to rename the structs..."
No, you do not need to.
But in future when designing data you should keep the structure names the same. Some beginners think that having different names is easier to work with... in fact when looping over multiple files using exactly the same variable name/s makes processing the data simpler, more efficient, and much more robust.
"What is the correct way to process this sequence of files? "
Assuming exactly one variable saved in each mat file:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
C = struct2cell(load(F));
S(k).data = C{1};
end
T = vertcat(S.data)

More Answers (1)

Rik
Rik on 3 Sep 2021
If you use struct2cell (either inside your loop or in a cellfun) you can extract the data itself. Then you should be able to use vertcat(data{:}).

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!