How to read table with specific word in name
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Devon Fisher-Chavez
il 22 Nov 2019
Commentato: Devon Fisher-Chavez
il 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 Commenti
Stephen23
il 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:
Risposta accettata
Stephen23
il 22 Nov 2019
Modificato: Stephen23
il 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Variables in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!