MATLAB: How to read table with specific word in name

readtable

Hi there,
I have a folder full of .dat files. Many of these .dat files have the word "fluxall" in them, for example "PJG_2019_fluxall.dat". I would like to use the "readtable" function to read all the .dat files with the word "fluxall" in them. So far I have:
files = struct2cell(dir('*fluxall*.dat'));
filenames = char(files(1,:));
ind = cellstr(1:length(filenames));
for i = 1:length(filenames)
eval(['Table_',ind{i},' = readtable(',filenames{i},');']);
end
The idea is to create a table named "Table_1,2,3…" for each "fluxall".dat file. Obviously it doesnt work.
Thanks!

Best Answer

Much simpler and more robust than your code:
D = 'path to the directory where the files are saved';
S = dir(fullfile(D,'*fluxall*.dat'));
for k = 1:numel(S)
S(k).data = readtable(fullfile(D,S(k).name));
end
C = {S.data}; % optional
Note that keeping the data in the structure S has the significant advantage of keeping the data and filenames in correspondence.