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

19 次查看(过去 30 天)
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 个评论
Ive J
Ive J 2021-9-3
编辑:Ive J 2021-9-3
I don't get it, do you have timetables or structs? Because they're not of the same class. The error you mentioned is for concatenation of structs and not tables. So assuming you have structs, one way would be to get rid of inconsistent field names and directly access to the content of that field:
V = ({});
for i = 1:n
fname = fieldnames(mystruct);
V{i} = mystruct.(fname{1}); % file has only one field
end
V = vertcat(V{:});

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2021-9-4
编辑:Stephen23 2021-9-4
"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)

更多回答(1 个)

Rik
Rik 2021-9-3
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{:}).

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by