How to read table with specific word in name
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Devon Fisher-Chavez
le 22 Nov 2019
Commenté : Devon Fisher-Chavez
le 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 commentaires
Stephen23
le 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:
Réponse acceptée
Stephen23
le 22 Nov 2019
Modifié(e) : Stephen23
le 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Variables dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!