MATLAB: Load multiple .mat files

multiple .mat files.

I am trying to load multiple .mat files through a script. Each file is a recorded channel, that contains data logged at high frequency (so some files are large) with a time stamp. The file name corresponds to the channel name allocated in a logging device. Ideally, I would like to end up with a table with all data combined from all .mat files.
I tried the following:
clear
PathName = uigetdir;
file_all = dir(fullfile(PathName,'*.mat'));
matfile = file_all([file_all.isdir] == 0);
clear file_all PathName
%d=dir('*.mat'); % get the list of files
x=[]; % start w/ an empty array
for i=1:length(matfile)
x=[x; load(matfile(i).name)]; % read/concatenate into x
if true
% code
end
but get the error: Error using vertcat Names of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of fields.
file names are different sizes, I don't know if this is the issue? Is there a simple way to load multiple files of numerical data? many thanks

Best Answer

Yes, you can't concatenate structures (the output of load) with different field names, which will always be the case with load. You can however easily concatenate tables with different columns names, so converting that structure in the loop to a table would work:
pathname = uigetdir;
allfiles = dir(fullfile(PathName,'*.mat'));
matfiles = allfiles([allfiles.isdir] == 0); %probably not needed since it's unlikely that a xxx.mat is a directory
fulltable = table();
for fileid = 1:numel(matfiles)
[~, filename] = fileparts(matfiles(fileid).name);
filetable = struct2table(load(fullfile(pathname, matfiles(fileid).name)));
filetable.Properties.VariableNames{2} = filename; %rename 2nd variable
fulltable = [fulltable, filetable(:, 2)]; %only copy second variable
end
Related Question