How to read table with specific word in name
4 views (last 30 days)
Show older comments
Devon Fisher-Chavez
on 22 Nov 2019
Commented: Devon Fisher-Chavez
on 22 Nov 2019
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!
3 Comments
Stephen23
on 22 Nov 2019
Note that the code is rather fragile, e.g.
- It assumes that the structure returned by dir always contains the fields in the same order, but their order is not specified.
- Use of numbered variables is a sign that you are doing something wrong. Most likely you should just use indexing, which makes looping over data much simpler and more efficient (and is what the MATLAB documentation recommends instead of eval).
Note that use of eval to generate numbered variables is one way the beginners force themselves into writing slow, complex, buggy code that is hard to debug:
Accepted Answer
Stephen23
on 22 Nov 2019
Edited: Stephen23
on 22 Nov 2019
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.
More Answers (0)
See Also
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!