MATLAB Answers

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

20 ビュー (過去 30 日間)
Oliver Higbee
Oliver Higbee 2021 年 9 月 3 日
編集済み: Stephen 2021 年 9 月 4 日
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 件のコメント
Christopher McCausland
Christopher McCausland 2021 年 9 月 3 日
I would suggest that you attach a couple of data files. This should make it a lot easier to help you.
Christopher

サインインしてコメントする。

採用された回答

Stephen
Stephen 2021 年 9 月 4 日
編集済み: Stephen 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{:}).

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by