MATLAB Answers

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

조회 수: 11(최근 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